Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to adding JavaScript in anchor tags

Hi StackOverflow community. I have a question about alternatives to adding JavaScript in the href of HTML anchor tags. I already know this is poor practice and instead of doing this:

<div id="some_div"><a href="JavaScript:myfunction();">Text</a></div>

I can just do this: Text

$('#some_div').on("click","a",function(e){
  myFunction();
});

My question is, how does this work if you have to pass variables into the function? For example:

<div id="some_div"><a href="JavaScript:myfunction('param1','param2')">Text</a></div>

Now keep in mind that the data in param1 and param2 will be different strings. How do you handle this case? The event listener needs to receive different data entered by the anchor tag. So how would the user add the param1 and param2 data when they use:

<div id="some_div"><a href="#">Text</a></div>

Thank you in advance.

like image 604
seroth Avatar asked Mar 23 '23 03:03

seroth


1 Answers

There are a lot of ways you can do it. One that comes to mind would be to use data-* attributes on the anchor:

<a href="#" data-param1="param1" data-param2="param2">Text</a>

var $this = $(this);
myFunction($this.data("param1"), $this.data("param2"));
like image 115
Explosion Pills Avatar answered Apr 25 '23 18:04

Explosion Pills