-1

I have javascript method which will remove applied class from DOM element on click. And the code is like

 $(function() {

     NS.toggleSortableClickHandler = function(element) {
         console.log("elememnt inside toggleSortableClickHandler  " + element)
         element.click = function onClick(e) {
             console.log("CALLED toggleSortableClickHandler")
         }
     }

     var ele = document.getElementById('mytoggler');
     console.log("document.getElementById('mytoggler') " + ele)
     NS.toggleSortableClickHandler(document.getElementById('mytoggler'));

 });

And the HTML code is:

<ol class="sortable" >
    <li id="mytoggler">List Item 11</li>
</ol>

So i expect that when i click on the li item console should print

CALLED toggleSortableClickHandler

But i didn't get anything when i click the item.

1

2 Answers 2

3

If you're going to install an event handler via the DOM property, it's "onclick", not "click":

     element.onclick = function onClick(e) {
         console.log("CALLED toggleSortableClickHandler")
     };

However, you're apparently using jQuery anyway, so you might as well use it:

     $(element).on("click", function onClick(e) {
         console.log("CALLED toggleSortableClickHandler")
     });
Sign up to request clarification or add additional context in comments.

Comments

0

First of all, you forgot the brackets, it should be

.click()

and you can't use the "=" operator after that. What you want to do isn't pure JavaScript, it's jQuery, and the syntax isn't correct.

In JavaScript,

element.click();

triggers the click event on element. In jQuery, if you want to assign a function to click event handler, you should use the syntax

element.click(yourFunction());

I would also suggest changing the name of your handler function, since onClick is an attribute used in HTML language to specify the click event handler. This may create some confusion in the readability of your code.

By the way, onClick is used like this, fyi.

<div onClick="myFunction()"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.