Question

Execute the jquery code only if div exist

here is the html code :

<div id="popup" class="popup_block" >
 <img src="images/PUB-histRIRE.jpg" alt="popup" />
</div>

and script :

<script type="text/javascript">
    $(document).ready(function(){

            popWidth = 690;
            popHeight = 550;
            popID = 'popup';

            var popMargTop = popHeight / 2;
            var popMargLeft = popWidth / 2;

            //Apply Margin to Popup
            $('#' + popID).css({ 
                'width': popWidth,
                'height': popHeight,
                'margin-top' : -popMargTop,
                'margin-left' : -popMargLeft,
                'visibility' : 'visible'
            }); 

            //Fade in Background
            $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
            $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer 

        //Close Popups and Fade Layer
        $('a.close, #fade, .popup_block').live('click', function() { //When clicking on the close or fade layer...
            $('#fade , .popup_block').fadeOut(); //fade them both out
            $('#fade').remove();
            return false;
        }); 

    });
    </script>

I like to execute the code only on page with the div... on page without thi div, just ignore. I can make a if by parsin the URL... but it look more complicated to me... any simple jquery trick ?

 21  19489  21
1 Jan 1970

Solution

 47
if($('#popup').length >0 ){
   //your code here 
}
2011-05-10

Solution

 8

Like this:

if($('div#popup').length) {
    // div exists
}
2011-05-10