0

I want to make function working only on page with specified element. I have search page, search fields and results are in search-block div. I want to bind function to this block, so function will not work on other pages (without <div id='search-block>...</div>)

I have next js code atm:

$(document).ready(function()
    // instructions for another page (handlers for some links)

    $(function(){
        setInterval(findSomething,1000);
    });     
});

It working fine on page with search-block div, but it works fine on the other pages too. Browser tries to run this function on all other pages. I don't need this.

I tried jquery bind, but it now worked for me, don't know why :(

$("#search-block").bind(function(){
    setInterval(findSomething,1000);
}); 

How I can bind handler to speciges too.fied block?

3
  • You may want to load "search-block" special js code only on the page with the $("search-block"), so you'll be sure that $("search-block") is exist. Commented Mar 10, 2014 at 14:44
  • How I can do this? If I will use it in such way strange error appearing . Smth like $0"$search-block") — illegal character there (0). I can't use $(document).ready(function(){ ... } in this script, because I already used it in another script. Commented Mar 11, 2014 at 19:48
  • Well, you can use multiple $().ready() (read this answer for additional information). Regarding to your question, I'd move all "search" logic to search-block.js and insert <script src="search-block.js"></script> to the page with $("search-block") object on. BTW you may want to read about something like requirejs or about any modular design pattern. Commented Mar 12, 2014 at 15:50

2 Answers 2

3

Instead of bind you have to check for the length of that elem:

$(document).ready(function(){
   if($('#search-block').length > 0){ // <---checks the availability
       setInterval(findSomething,1000);
   }
}); 
Sign up to request clarification or add additional context in comments.

Comments

2

Bind is always used with an event to bind to:

$( "#foo" ).bind( "mouseenter mouseleave", function() {

});

if you want to execute that only when the block is available on the page, use this:

if ($('#search-block').length) {
    setInterval(findSomething,1000);
}

This checks the number of times #search-block is found on the page and if it is not 0(false) it executes the code.

1 Comment

Your second one is better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.