1

I'm working on some code that contains a click event for a span element (This piece of code is part of the function that creates the span):

$("span[class=addnewsqlwherevalue][id='" + opts.counters[3] + "']").click(
function(e) { ...});

It is executed immediately after it is defined there and also when I click the specified span element although I only want it to be executed when I click on the element.

I also tried:

function clickSpan(e) {...} 
$("span[class=addnewsqlwherevalue][id='" + opts.counters[3] + "']").onclick = clickSpan;

In the above case it is executed never.

$("span[class=addnewsqlwherevalue][id='" + opts.counters[3] + "']").on('click', function(e) {...}); // same as the first approach

I looked at similar questions but they didn't contain a solution that worked. This code is not from me, so I might miss something but I assume that nowhere in the code this onclick event is executed (because the function is called exactly when it is created).

Please bear with me, I'm new to javascript and I need to find several bugs in a big project.

Verena Haunschmid
  • 1,252
  • 15
  • 40
  • did you try using the bind method to bind the click event instead or the click method? – developer82 Jan 07 '14 at 08:07
  • @developer82 bind is deprecated and should not be used. The `click` and `on` syntax used is fine. You say that code is the part which *creates the span* - there is no creation code here, only binding to the click event. You should show all relevant code for this span – CodingIntrigue Jan 07 '14 at 08:07
  • then maybe try using is first on all span objects, and see if it auto fires. – developer82 Jan 07 '14 at 08:09
  • 3
    `on()` is the right way to define the event and cannot be executed automatically. So I would ask to check if the click event is not invoked in another place in the code using `.click()` or `.trigger('click')` – sdespont Jan 07 '14 at 08:10
  • If you remove the id part, the code snippet is working perfectly in that case. [here is the fiddle for it](http://jsfiddle.net/cvSgj/1/). It shows opts not defined in console.. – Vikas Arora Jan 07 '14 at 08:16
  • @sdespont Thank you very much, I didn't know about trigger. And I have no clue why it was called there. Now it works! – Verena Haunschmid Jan 07 '14 at 08:20
  • @ExpectoPatronum great, I have copy my comment as answer to close the question. – sdespont Jan 07 '14 at 08:38

1 Answers1

1

Answer has been found in the question comment. Here is just a copy/paste of the comment to close the question properly.

on() is the right way to define the event and cannot be executed automatically. So I would ask to check if the click event is not invoked in another place in the code using .click() or .trigger('click')

sdespont
  • 13,915
  • 9
  • 56
  • 97