1

I have one item (#engaged) to which I have to add a class on jQuery click. There are 20 variants on which if users clicks a different class will be added to #engaged.

For example, if the user clicks #one, class .one should be added to #engaged. Similarly, if the user clicks #two, class .two should be added to #engaged.

I know how to do it, but the problem is that it only works one or two times on page load. More clicks are not accepted, even if I remove the previous added class on next click. How can I make it accept more clicks without reloading the page?

$("#one").click(function () {
    $("#engaged").mouseenter(function () {
        $(this).addClass("one");
    });
    $("#engaged").mouseleave(function () {
        $(this).removeClass("one");
    });
});

$("#two").click(function () {
    $("#engaged").mouseenter(function () {
        $(this).addClass("two");
    });
    $("#engaged").mouseleave(function () {
        $(this).removeClass("two");
    });
});

..... and so on

Adi Inbar
  • 12,097
  • 13
  • 56
  • 69
imran
  • 13
  • 3

2 Answers2

1

If you are using the .click event, it will not work on dynamically created elements:

$(‘.selector’).click(function () {

Try using .on('click') instead:

$(‘selector’).on('click', '.selector', function () {

Reference: In jQuery, how to attach events to dynamic html elements?

Reference 2: Difference between .on('click') vs .click()

Community
  • 1
  • 1
L_7337
  • 2,650
  • 28
  • 42
  • @isherwood I do not understand what you mean in your edit, "(which you certainly should)" – L_7337 Jul 21 '14 at 20:28
  • My apologies. I edited the wrong answer in my haste. Undoing. – isherwood Jul 21 '14 at 20:53
  • I see that this answer was selected, though I have no idea why. There's nothing about dynamically-created elements in the question. – isherwood Jul 21 '14 at 21:21
  • @L_7337 well, there is still some problem after 5 or 6 clicks, please try to select different items in this page and you will come to know that still problem exists. http://topgravity.com/engaged-social-menu/ – imran Jul 22 '14 at 22:22
  • Everything seems to work indefinitely for me. Please clarify what element(s) the problem occurs on, or ask a new question. – isherwood Jul 23 '14 at 12:02
0

I'll take a crack at it, assuming you have a common class on your click targets (which you certainly should).

$('.myCommonClass').click(function() {
    var myStr = $(this).attr('id').replace('#', '');

    $('#engaged').attr('class', '').addClass(myStr);
});

http://jsfiddle.net/isherwood/zeNVW/

isherwood
  • 58,414
  • 16
  • 114
  • 157
  • thanks for giving me some time. Your answer works perfectly as i checked in jsfiddle. But the problem is that its too heavy for me to grasp. I am new to jquery, still problem exists is the correct marked answer of L_7337, please check my comment there. – imran Jul 22 '14 at 22:28