Reputation: 482
Is it possible to make <a href="">
to do 2 things? One to javascript:
and the other to jump to a section in a documents using <a id="">
and a #
mark.
In short I am looking for something like this:
<a href="javascript:someFunction('params');#paragraphSectionId">Link</a>
Upvotes: 1
Views: 1161
Reputation: 253396
I'd suggest using unobtrusive JavaScript, moving the event-handling away from your HTML:
function doSomething(){
console.log("You clicked on the " + this.tagName.toLowerCase() + " element.");
}
var link = document.getElementById('aElementID');
link.onclick = doSomething;
This does, though, require an id
on the a
element:
<a href="#paragraphSectionId" id="aElementID">Go to the paragraph</a>
You could, though, use a class-name instead, though this involves binding the functionality to multiple elements, with a for
loop (or similar); given the a
elements having the form:
<a href="#paragraphSectionIdOne" class="linkClassName">Go to the paragraph</a>
<a href="#paragraphSectionIdTwo" class="linkClassName">Go to the other paragraph</a>
The JavaScript would become:
function doSomething(){
console.log("You clicked on the " + this.tagName.toLowerCase() + " element.");
}
var links = document.getElementsByClassName('linkClassName');
for (var i = 0, len = links.length; i < len; i++){
links[i].onclick = doSomething;
}
You could even bind the event-handling to an ancestor element, and basing the response on which element received the event; this would allow HTML of the form:
<div id="arbitraryAncestorElement">
<a href="#one">Go to One</a>
<ul>
<li><a href="#two">Go to Two</a></li>
<li><a href="#three">Go to Three</a></li>
</ul>
</div>
With the JavaScript:
function doSomething(event){
if (event.target.tagName.toLowerCase() === 'a') {
console.log("You clicked on an 'a' element.");
}
}
var ancestor = document.getElementById('arbitraryAncestorElement');
ancestor.onclick = doSomething;
Upvotes: 2
Reputation: 236
Of course, you can do this:
<a href="#paragraphSectionId" onclick="someFunction('params')">Link</a>
Upvotes: 2
Reputation: 27765
Yes, use onclick
property:
<a href="#paragraphSectionId" onclick="someFunction('params');">Link</a>
Upvotes: 5