0

I'm not initially developper but for my portfolio I need to dive again in the incredible world of jQuery !

I wanted to optimize my code and create functions because I call it a lot of times, but for a reason I don't know, this code isn't working, let's see a part of it :

$( document ).ready(function() {

function openMenu(){
    alert('ok');
}

$('.home-left').click(openMenu());

This code would normally work, but it is only working on DOM load, and not after. If I place it outside, it isn't working at all.

Maybe I do something wrong ?

Thank you !

Floran
  • 11
  • 5

2 Answers2

0
$('.home-left').click(function(){
 openMenu();
})
Harkirat singh
  • 599
  • 6
  • 19
0

The event handler function should be referenced.

$('.home-left').click(openMenu);

$( document ).ready(function() {

function openMenu(){
    alert('ok');
}

$('.home-left').click(openMenu);

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="home-left">Home Left</div>
Charlie
  • 22,886
  • 11
  • 59
  • 90
  • It is working but I don't really see the difference except removing the () ? In my case I had the document ready function, the function detailed, the event click that called the function, and of course in my HTML jquery was called :) – Floran Jun 20 '21 at 19:01
  • Brackets themselves are the BIG difference. Brackets means execute the function. But it is only reference to the function you should give to the event handler. Yo don't have to execute the function. – Charlie Jun 21 '21 at 02:53