css - jquery and creating styles, how to check if the style already exists -
hi people have looked around cant seem find answer i'm looking for.
i have search page makes ajax calls, returns json data creates style based on returned data , appends section of dom. creation of styles working ok, if new search made style duplicated , $(#element).slidetoggle() function gets duplicated , slidetoggle opens , closes immedietly.
ypu can see page here: http://www.reelfilmlocations.co.uk/new%20search/fullsearch_jq_keys.php
(use test data hounslow, north london , categories: cemeteries) if same search made twice styles results gets duplicated, , slide toggle behaviour duplicated.)
my question how check if style in existence.
the script creates style follows:
function makecss(id){ var myurl = 'getboroughinfo.php'; $.ajax({ url: myurl, type: 'post', data: 'myid='+id, datatype: 'json', error: function(xhr, statustext, errorthrown){ // work out error , display appropriate message }, success: function(mydata){ var items = mydata.boroughs[0]; //console.log('borough: '+mydata.boroughs); $("<style type='text/css'> #link_"+items.borough_id+"{ color:"+items.color+"; font-weight:bold; float:left; margin-left: 10px; cursor: pointer; padding: 1px; border: 1px solid "+items.color+";} </style>").appendto("head"); $("<style type='text/css'> #borough_"+items.borough_id+"{ color:"+items.color+"; font-weight:bold; } </style>").appendto("head"); $("<style type='text/css'> #searchhead_"+items.borough_id+"{ color:#000000; font-weight:bold; background-color:"+items.color+"; opacity: 1.0; cursor: pointer;} </style>").appendto("head"); //apply opacity //$('#borough_'+items.borough_id).css({}); $('#borough_links').append('<div id="link_'+items.borough_id+'">'+items.borough_name+'</div>'); $('#results').append('<div id="searchhead_'+items.borough_id+'">'+items.borough_name+'</div>'); $('#results').append('<div id="borough_'+items.borough_id+'"></div>'); $('#link_'+items.borough_id).live('click', function(){ $('#borough_'+items.borough_id).slidetoggle('slow', function() { // animation complete. }); }); $('#searchhead_'+items.borough_id).live('click', function(){ $('#borough_'+items.borough_id).slidetoggle('slow', function() { // animation complete. }); }); } }); };
this line of code creates 1 of styles:
$("<style type='text/css'> #link_"+items.borough_id+"{ color:"+items.color+"; font-weight:bold; float:left; margin-left: 10px; cursor: pointer; padding: 1px; border: 1px solid "+items.color+";} </style>").appendto("head");
so how check if exists in document already???? simple if statement suffice needs think.
you can use :contains selector. e.g:
if($("style:contains('#link_" + items.borough_id + "')").length < 1) { $("<style type='text/css'> #link_"+items.borough_id+"{ color:"+items.color+"; font-weight:bold; float:left; margin-left: 10px; cursor: pointer; padding: 1px; border: 1px solid "+items.color+";} </style>").appendto("head"); }
Comments
Post a Comment