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?

Sharikov Vladislav
  • 7,049
  • 9
  • 50
  • 87
  • 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. – agudulin Mar 10 '14 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. – Sharikov Vladislav Mar 11 '14 at 19:48
  • Well, you can use multiple `$().ready()` (read [this answer](http://stackoverflow.com/questions/12797257/call-order-of-jquery-ready-callback/12797330#12797330) for additional information). Regarding to your question, I'd move all "search" logic to `search-block.js` and insert `` to the page with $("search-block") object on. BTW you may want to read about something like [requirejs](http://requirejs.org/) or about any modular design pattern. – agudulin Mar 12 '14 at 15:50

2 Answers2

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);
   }
}); 
Jai
  • 74,255
  • 12
  • 74
  • 103
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.

DreamWave
  • 1,934
  • 3
  • 28
  • 59