HTML make text clickable without making it a hyperlink

I want to add the ability to have the option to click on certain HTML text and have the correct JavaScript code be executed.

How can I do this?

4 Answers

For semantics I'd use a <button> element like this:

<button>Clicky</button>

to make the button look like normal text you can use CSS:

button.link { background:none; border:none; }

and for easiness of handing click I'd use jQuery like so:

$(".link").on("click", function(e) { // e is the event object // this is the button element // do stuff with them
});

Although if you have an ID attribute on the button you can use plain JS like this:

var button = document.getElementById("your-button-id");
button.addEventListener("click", function(e) { // e is the event object // e.target is the button element // do stuff with them
});
<div onClick="function()"> your text here </div>
1

The apropriate element for an interactive control that isn't a link somewhere is a <button>Label</button> or (<input type="button" value="Label">). (You can always style away the border and background with CSS).

You can bind a click event handler to it using the standard DOM APIs (or a library that abstracts them such as YUI or jQuery).

place the text in a span or other element with a class <span>text</span> and then use javascript to add an event listener (preferably at the end of your html. for brevity, I'll demonstrate with jQuery, though it could be done with native javascript.

<script> $('.yourClass').on('click',function(){ //your javacript });
</script>

Alternatively you could do search through all the page for instances of that word, though I would not recommend that as it would really slow things down.

1

You Might Also Like