Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute the jquery code only if div exist

Tags:

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 ?

like image 431
menardmam Avatar asked May 10 '11 13:05

menardmam


People also ask

How do you check Div is exist or not in jQuery?

In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements. To check if an element which has an id of “div1” exists.

What is $() in jQuery?

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements. A jQuery action() to be performed on the element(s)

How do I check if an element is present in a Web page?

Using driver. In order to check if an element is present on a webpage, we make use of driver. findElements() method. As we know that driver. findElements() method returns a list of webElements located by the “By Locator” passed as parameter.


2 Answers

if($('#popup').length >0 ){
   //your code here 
}
like image 84
mcgrailm Avatar answered Oct 22 '22 21:10

mcgrailm


The way to do this is (or was) to check the length property like so:

if ($("#"+ popID).length > 0){
  // do stuff
}
like image 42
Russ Clarke Avatar answered Oct 22 '22 20:10

Russ Clarke