OutFall
OutFall

Reputation: 482

a href - how to execute javascript and jump to a section?

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

Answers (3)

David Thomas
David Thomas

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;

JS Fiddle demo.

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;
}

JS Fiddle demo.

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;

JS Fiddle demo.

Upvotes: 2

jaicab
jaicab

Reputation: 236

Of course, you can do this:

<a href="#paragraphSectionId" onclick="someFunction('params')">Link</a>

Upvotes: 2

antyrat
antyrat

Reputation: 27765

Yes, use onclick property:

<a href="#paragraphSectionId" onclick="someFunction('params');">Link</a>

Upvotes: 5

Related Questions