The right way to run javascript from html

What is the way to create a graphic component (more precisely, the twitter.bootstrap icon) on the html website that calls the java script.

You can either make a button or place an icon on it, but it does not look pretty IMHO. Or you can use the href tag,

<a href="#" name="ad_fav" onclick= CALLFUNCTION> <i class="icon"></i></a> 

But what is the cleanest way to achieve this? It would be nice if the icon could change after clicking it.

How is this implemented, for example, the upvote button in stackoverflow?

+6
source share
4 answers

Another way:

 function myFunc () { // code here } var element = document.getElementsByClassName("icon"); element[0].addEventListener("click", myFunc); 
+4
source

Just type href in <a> be 'javascript:', example:

 <a href="javascript:alert('hello there! this works!')" name="ad_fav"> <i class="icon"></i></a> 

Replace alert (...) with function call if you need

+1
source

You have no binding to the binding element:

 <img src="[path to twitter.bootstrap icon]" onclick="yourJavaScriptFunction" /> 
+1
source

Why don't you use jquery for a function?

 $(document).on("click", "a.icon", function (e) { e.preventDefault(); }); 
0
source

Source: https://habr.com/ru/post/947986/


All Articles