PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

[FIXED] What is the proper way to dynamically create event handlers in JavaScript for many links?

 October 15, 2022     dom, javascript, jquery, jquery-events     No comments   

Issue

I am generating a number of links on a page. I want to add onmouseover, onmouseout, and onclick event handlers to the links after the DOM has loaded, i.e. use jQuery to loop through the links and attach the handlers. However the problem is each handler requires information specific to that link.

So as an example if I don't want to do it after the DOM has loaded it would look like:

<a href="" onmouseover="somefunc(1,100);"></a>

So in the above example, 1 and 100 is data read from a database and output on the page, and these need to be passed to the function. So how do I output this information for this link if I'm gonna attach an event handler at load time. Is this correct...?

<a href="" data="1,100">

In other words, I create my own attribute and later grab that information when attaching the event handler? Is that the standard way of doing it or is there a better way?


Solution

Since you mention jQuery in your question (but not tagged) I am going to assume it is a valid option.

If you are using jQuery > 1.4.3, jQuery will automaticlaly parse data-* attributes.

<a href="" data-number1="1" data-number2="100">

And in your jQuery click handler:

$("a").click(function(){
  var num1 =  $(this).data("number1");
  var num2 =  $(this).data("number2");
});

You can also store a json object in your data-* as well.

<a href="" data-numbers="{'num1: 1, 'num2': 2}">

$("a").click(function(){
  var numbers =  $(this).data("numbers");
  //numbers.num1 and numbers.num2
});


Answered By - Mark Coleman
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing