-1

I have two divs with a button which when clicked, changes the class (col-lg-6 to col-lg-1) of a div and adds the sectionMinimized class. I'm trying to make it that when the entire div with the sectionMinimized class is clicked, the console logs "hey". For some reason it doesn't work unless I add the:

$('.sectionMinimized').click(function() {
    console.log("HEY!");
});

in the console.

Here's the code:

    $('.expand-section').click(function() {
    buttonId = $(this).attr('id');
    console.log(buttonId);
    if(buttonId === 'expandEvent') {
        $('.event-section').removeClass('col-lg-6');
        $('.event-section').addClass('col-lg-3 order-1');
        $('.event-section').find('button').addClass('hidden');
        $('.permanent-section').removeClass('col-lg-6');
        $('.permanent-section').addClass('col-lg-1 order-2');
        $('.event-section').addClass('sectionMinimized');
        $('.permanent-section').find('h2').addClass('header-minimize');
        $('.permanent-section').find('p').addClass('hidden');
        $('.permanent-section').find('button').addClass('hidden');
        console.log($('.sectionMinimized').attr('id'));
    } else {
        $('.permanent-section').removeClass('col-lg-6');
        $('.permanent-section').addClass('col-lg-3 order-1');
        $('.permanent-section').find('button').addClass('hidden');
        $('.event-section').removeClass('col-lg-6');
        $('.event-section').addClass('col-lg-1 order-2');
        $('.event-section').addClass('sectionMinimized');
        $('.event-section').find('h2').addClass('header-minimize');
        $('.event-section').find('p').addClass('hidden');
        $('.event-section').find('button').addClass('hidden');
        console.log($('.sectionMinimized').attr('id'));
    }
});

$('.sectionMinimized').click(function() {
    console.log("HEY!");
});

Can someone advise on how I can get this to run?

  • 1
    Your code selects existing `.sectionMinimized` elements at the time you're attaching the event. If there are not any of those elements in the DOM (you're adding the class later!), event is not attached. – Teemu Jan 11 '19 at 18:02

2 Answers2

0

The problem is that at the time you are setting your listener for $('.sectionMinimized') at that time the class doesn't exists, because you are adding dynamically, so all you need is to delegate the event to that class, so how to do it ? just like that:

$('.event-section').on('click', '.sectionMinimized', function() {
    console.log("HEY!");
});

that should do the trick

Juorder Gonzalez
  • 1,642
  • 1
  • 8
  • 10
-2

Here, the event is attached when the document is ready

$(function(){
  $('.sectionMinmized').click(function() {
    console.log("HEY!");
  });
});


Executed when doc ready.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="sectionMinmized">Click</button>
Bibberty
  • 4,670
  • 2
  • 8
  • 23