1

I'm working on a small image gallery which just enlarges a picture when you click on it. I'm making it with jQuery by adding and removing classes.

$(".image").click(function() {
    $(this).addClass("big").removeClass("image").css("position", "fixed").animate({
        height: '480px',
        width: '717px',
        top: '5%',
        left: '50%',
        marginLeft: '-358px',
        borderWidth: '40px',
        zIndex: '100'
    }, "slow");
});
$(".big").click(function() {
    $(this).removeClass("big").addClass("image").css("position", "auto").animate({
        height: '234px',
        width: '350px',
        top: 'auto',
        left: 'auto',
        marginLeft: '0px',
        borderWidth: '0px',
        zIndex: 'auto'
    }, "slow");
});

The problem i'm having is that it does remove the image class and adds the big class but it doesn't work the otherway around, what am I doing wrong?

The Dutchman
  • 131
  • 1
  • 11
  • can you put all code here OR can share with me demo link – Sunny S.M Dec 09 '15 at 19:13
  • seems you should remove the $('.big').removeClass('.big'); in beginning of image click and $('.image').removeClass('.image'); in beginning of .big click – Mohamed-Yousef Dec 09 '15 at 19:13
  • It looks you'll need to [delegate events](https://learn.jquery.com/events/event-delegation/) for elements that don't exist upon page load. For example, no elements have class "big" when the page loads, so that handler is not bound to anything. – showdev Dec 09 '15 at 19:14
  • Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – showdev Dec 09 '15 at 19:16

1 Answers1

0

You want to delegate the second event since upon initially loading the page no element has that class, so the selector returns zero elements and nothing is attached. Using delegation you can attach the event to a higher element, usually best to put it on the closest parent you can, which will pass the event to the dynamically created element later when he exists.

Example:

$("body").on('click', '.big', function() {
    $(this).removeClass("big").addClass("image").css("position", "auto").animate({
        height: '234px',
        width: '350px',
        top: 'auto',
        left: 'auto',
        marginLeft: '0px',
        borderWidth: '0px',
        zIndex: 'auto'
    }, "slow");
});

I used body here since I am not familiar enough with your HTML to know the closest element. This basically says the body element will watch for click events and if that click event happens to be on a element with the class big it will pass the event off to it.

AtheistP3ace
  • 9,611
  • 12
  • 43
  • 43