0

I have got two jquery functions. When calling the first function classes are being removed and two onclick attributes are being changed.

But after calling the function to remove the classes the second function won't work, so the classes cannot be added anymore and the onclick event, too.

Edit 1: As already said the first function is working! The onclick events are being changed and the classes are being removed. It does not work when adding the same classes and functions again within the second function! When adding a new class it is working, but it is not working when adding one of the removed classes or onclick events!

Here's the code:

// show info
function showKursInfo() {
    $(".kright").removeClass("kursMobileOpen");
    $(".kleft").removeClass("kursMobileInfo");

    $(".kright").attr("onclick","#");
    $(".kheader").attr("onclick","hideKursInfo('someInfo');");
}
// hide info
function hideKursInfo() {
    $(".kright").addClass("kursMobileOpen");
    $(".kleft").addClass("kursMobileInfo");

    $(".kright").attr("onclick","showKursInfo('someInfo');");
    $(".kheader").attr("onclick","#");
}

Thanks for your help!

And to the ones who are disliking the question: Please tell me why this is a bad question?

moritzm3
  • 1,197
  • 1
  • 7
  • 6
  • Please add HTML code and if possible add to codepen or jsfiddle to see problem at all – ristapk Aug 12 '16 at 10:41
  • You do not need to set `onclick` attributes with jQuery. The whole point is that it provides you with a set of event methods: https://api.jquery.com/category/events/mouse-events/ – BadHorsie Aug 12 '16 at 10:49
  • @BadHorsie But this is actually not a solution because of the classes, and this was the main question! – moritzm3 Aug 12 '16 at 10:59
  • already vote up, by the way attr is for what? – Fiido93 Aug 12 '16 at 11:09

1 Answers1

2

Don't use attr for register click events. Use click or on!

// show info
function showKursInfo() {
    $(".kright").removeClass("kursMobileOpen");
    $(".kleft").removeClass("kursMobileInfo");

    $(".kright").off("click");
    $(".kheader").on("click", hideKursInfo);
}

// hide info
function hideKursInfo() {
    $(".kright").addClass("kursMobileOpen");
    $(".kleft").addClass("kursMobileInfo");

    $(".kright").on("click", showKursInfo);
    $(".kheader").off("click");
}
eisbehr
  • 11,374
  • 7
  • 30
  • 56
  • And this is not solving the problem cause of the classes. – moritzm3 Aug 12 '16 at 10:54
  • Then you should give us more code, errors or something. Because it is working that way. See here: https://jsfiddle.net/wejLjrxr/ @moritzm3 – eisbehr Aug 12 '16 at 11:00
  • And to prove, your old code it not working: https://jsfiddle.net/wejLjrxr/1/ @moritzm3 – eisbehr Aug 12 '16 at 11:02
  • What exactly are you trying to achieve with the kheader click listener? @eisbehrs is right onclick attr is a bit confusing https://jsfiddle.net/xzxh6sm9/ – Murray Wynnes Aug 12 '16 at 11:05