I'm creating a page with two section where I load content .load()
into #container
by clicking on the titles.
<div id=dogs>[dogs]</div>
<div id=cats>[cats]</div>
<div id=#container></div>
<div class=button_dogs></div>
My problem
I have a right-bottom fixed button that I only want it to be displayed in the section #dogs
section (not in the cat section), and the page initializes by default with #dog
section, so my code is something like that
$("#container").load("content.php?s=dogs"); //initial
$("#cats").click(){function(){
$("#container").load("content.php?s=cats"); //after click
$(".button_dogs").hide();
$(window).unbind(".button");
}}
$("#dogs").click(){function(){
$("#container").load("content.php?s=dogs"); //after click
$(".button_dogs").show();
$(window).bind("scroll.button");
}}
This is the fixed button binded to window
$(".button_dogs").hide();
$(window).bind("scroll.button", function(){
if($(this).scrollTop()>50) {
$(".button_dogs").show()
} else {
$(".button_dogs").fadeOut()
}
});
I don't know what I'm doing wrong, When clicking on #dogs
it binds again the fixed button function, but it doesn't work with the effects of before.This is the line I have doubts about (from #dogs click event)
$(".button_dogs").show();
$(window).bind("scroll.button");
Firstly, you need to wrap the element IDs and classes with quotes. Some browsers don't care but others do. Also, don't prefix the container ID with a hash unless you're using a selector to find it...
<div id="dogs">[dogs]</div>
<div id="cats">[cats]</div>
<div id="container"></div>
<div class="button_dogs"></div>
You can do what you're trying to do without removing and re-adding the event handler function. This method will use a data attribute on the content div to specify what the content type is, so the scroll handler can simply exit if it's not dog content...
// keep a reference to the content div, rather than keep looking it up...
var $container = $("#container");
$("#cats").click(function() {
$container
.load("content.php?s=cats")
.data("content", "cats"); // add a data attribute that has the value "cats"
});
$("#dogs").click(function() {
$container
.load("content.php?s=dogs")
.data("content", "dogs"); // add a data attribute that has the value "dogs"
});
$(".button_dogs").hide();
$(window).bind("scroll.button", function() {
// if the content is not dogs then exit this function...
if ($container.data("content") != "dogs") return;
if ($(this).scrollTop() > 50) {
$(".button_dogs").show();
}
else {
$(".button_dogs").fadeOut();
}
});
$("#dogs").trigger("click"); // click the dogs button to initialize the page
I also added the variable $content
which is a reference to the #content
element, so you don't need to keep looking it up every time you reference it. Repeated lookups are not that expensive with an ID, but it's a good habit to get into.
Finally, I added code to click the dog button when the page loads, rather than have to duplicate the code that is executed when that happens.