Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right way of triggering a javascript from html

What is the way for having a graphical component (more precisely a twitter.bootstrap icon) in an html website calling a java script.

One could either make a button and putting the icon on it, but this does not look nice IMHO. Or one could use the href tag,

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

But what is the cleanest way of achieving this? It would also be nice if the icon could change after it was clicked.

How it for example the upvote button in stackoverflow implemented?

like image 524
user695652 Avatar asked Jun 24 '13 12:06

user695652


People also ask

How do I pull JavaScript from a website?

View web page source codePress the Ctrl + U keyboard shortcut. Right-click an empty area on the web page and select the View page source or similar option in the pop-up menu.


3 Answers

Another way:

function myFunc () {
// code here
}

var element = document.getElementsByClassName("icon");
element[0].addEventListener("click", myFunc);
like image 56
Stefan Avatar answered Sep 21 '22 04:09

Stefan


Just make the href of the <a> be 'javascript:', example:

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

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

like image 21
Alex Coleman Avatar answered Sep 19 '22 04:09

Alex Coleman


You don't have do wrap it with an anchor element:

<img src="[path to twitter.bootstrap icon]" onclick="yourJavaScriptFunction" />
like image 24
Marvin Emil Brach Avatar answered Sep 21 '22 04:09

Marvin Emil Brach