Reason JQuery 'addClass' not working in function (?)


I’m a little confused as to why my JQuery ‘addClass’ method seems to stop working when placed in a function call.

/* $("#logo").addClass(“fade-out”); */

function performSearch() {
console.log(“Button has been pressed”);


If I un-comment the first line outside of the function one can see ‘addClass’ is working correctly. Further, I know the function is being called correctly because console.log triggers as expected. However for some reason then the addClass does not have the same effect, or seems to do nothing… A little confused…

Code here:

Change the following:

<button onclick="performSearch()">Search</button>


<button onclick="performSearch(); return false;">Search</button>
1 Like

Thanks Randell,

That seems to work-- But do you have any idea why?!?. Even putting the ‘return statement’ at the end of the ‘performSearch()’ function itself doesn’t seem to work. Seems a little weird-- What is it expecting that adding the return to the call, not even to the function itself, won’t suffice ?

The return value of an event handler determines whether or not the default browser behavior should take place as well. You have a click event on your form’s button. When there is only one button in a form, it is assumed to be of type “submit”, so when clicked, it tries to submit the form. You have no action specified, so it basically just reloads to page. By adding the return false; after the function call, you prevent the form from submitting and the function code will execute.

You could use your existing onclick=“performSearch()” code if you get rid of the form tags (<form> and </form>) surrounding the button.

Oh, I see-- Doing further searches I guess this is a ‘thing’ regarding event handlers and on-click events.

Some more info if this is useful to anyone else:

and here:

Okay, that makes more sense to me now as otherwise with <form> as with <a href> in the Youtube example the page will try and invoke the default relevant behavior for the tag.

This was not obvious to me at first but makes more sense now. Thanks for your help.