Question

I'm trying to open and close a drawer using jQuery/JavaScript to change the drawer's height from 25px (where it is hidden behind another element) to 250px where it pops open and is visible. I have an up-arrow that acts as a button. It switches class to become a down-arrow as the drawer opens. Every thing in the up-arrow portion of the code works. For some reason the down-arrow part is not working and the drawer won't close. I have a sneaking suspicion that this is because I'm trying to add a click event to a class that has not yet been added to the DOM, but I'm not sure if that's right. Even if that is right I don't know how to fix it. Any ideas?

   $('.arrow-up').click(function() {
        $('.portfolio-details').css('height',250);
        $('.portfolio-details h2 span').removeClass('arrow-up');
        $('.portfolio-details h2 span').addClass('arrow-down');
        });

    $('.arrow-down').click(function() {
        $('.portfolio-details').css('height',25);
        $('.portfolio-details h2 span').addClass('arrow-up');
        $('.portfolio-details h2 span').removeClass('arrow-down');
        });
Was it helpful?

Solution

Try event delegation, since you are working with dynamic selector values

 $(document).on('click', '.arrow-up', function() {
    $('.portfolio-details').css('height',250);
    $('.portfolio-details h2 span').removeClass('arrow-up');
    $('.portfolio-details h2 span').addClass('arrow-down');
    });

$(document).on('click', '.arrow-down', function() {
    $('.portfolio-details').css('height',25);
    $('.portfolio-details h2 span').addClass('arrow-up');
    $('.portfolio-details h2 span').removeClass('arrow-down');
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top