I'm trying to do something very simple. Basically I have a clickable div 'hot spot', when you click that it fills the screen and displays some content. I achieved this by simply changing the class of div, removing 'spot' and adding 'grown' and there's a little CSS animation to make it grow. This works fine.
The problem is, within this div there is a close_button, which at the moment is just text. I want this to switch the classes back - i.e. remove grown and readd spot. It doesn't do this when clicked. I believe it's to do with the element not having those classes when the DOM loads, but I'm new to jQuery and don't know how to work around this.
I think there's probably a much more sensible way of doing it, could someone point me in the right direction? I'd be very grateful. I've tried using toggleClass instead to no avail.
$( document ).ready(function() {
$(".clickable").click(function() {
$(this).addClass("grown");
$(this).removeClass("spot");
});
$(".close_button").click(function() {
alert (this);
$("#spot1").removeClass("grown");
$("#spot1").addClass("spot");
});
});
UPDATE:
I am using this code now,
$( document ).ready(function() {
$(document).on("click", ".close_button", function () {
alert ("oi");
$("#spot1").addClass("spot");
$("#spot1").removeClass("grown");
});
$(document).on("click", ".clickable", function () {
if ($(this).hasClass("spot")){
$(this).addClass("grown");
$(this).removeClass("spot");
}
});
});
strangely the close_button function still won't add 'spot' or remove 'grown' though it will add any other classes and it will remove other classes... I added the if clause because I thought perhaps both function were being triggered at the same time, undoing each other, but it seems to make no difference
I actually just resolved an issue I was having by swapping around the order that I was altering the properties in. For example I was changing the attribute first but I actually had to remove the class and add the new class before modifying the attributes. I'm not sure why it worked but it did. So something to try would be to change from
$("XXXX").attr('something').removeClass( "class" ).addClass( "newClass" )
to$("XXXX").removeClass( "class" ).addClass( "newClass" ).attr('something')
.I think you're almost there. The thing is, your
$(this)
in the "close button" listener is not the clickable div. So you want to search it first. try to replace$(this)
with$(this).closest(".clickable")
. And don't forget thee.stopPropagation()
as Guilherme is suggesting. that should be something like:Try this :
I hope I understood your question.
why not simplify it?
jquery
This way it's much easier to maintain.
made a fiddle: http://jsfiddle.net/filever10/3SmaV/