Erick Watson
Erick Watson

Reputation: 13

How to assign javascript variable with id of a link tag before going to the link

How do I hijack a link tag and assign a variable with id of a link tag before going to the url?

MY HTML Code

<div id="course" class="row">
    <div class="col-md-6"><a href="read.html" id="m1">Course 1</a></div>
    <div class="col-md-6"><a href="read.html" id="m2">Course 2</a></div>
<div>

MY JAVASCRIPT CODE

document.getElementById("course").addEventListener("click", courseInfo);

function courseInfo(){

    var selectedCourse = the id of the course selected;

    //assign to localstorage
    localStorage.setItem("courseid", selectedCourse);
    //go to courseinfo.html
    window.location.href = 'courseinfo.html';

}

I'm trying to get the Id of the course and the set it to the local storage so that when the courseinfo.html is loaded if will make request ajax and parse the course json format to fill the page.

Please help

Upvotes: 1

Views: 111

Answers (2)

Nir Levy
Nir Levy

Reputation: 4740

As @trincot suggested you can do this on the receiving end.

If, however, you do need to capture the id of the clicked link when it is clicked, you need to add the event handler on the links themselves and then use the event recieved to handle the data, like so

var x;
var links = document.getElementsByTagName("A");

for(x in links) {
    if (links[x] instanceof Element) {
        links[x].addEventListener('click',doX, false);
    }
}

function doX(e) {
    alert(e.currentTarget.id);
}

Please note that on fast browsers, the browser may not completely finish running doX before the page gets refreshed and the context vanishes, so this not a very safe method to do things, unless you prevent the default action using e.preventDefault and handle the link yourself.

Upvotes: 0

trincot
trincot

Reputation: 350137

You should not use localStorage for this, but just pass the information via a URL argument:

On the first page, put the course code in the href URL, like this:

<div id="course" class="row">
    <div class="col-md-6"><a href="courseinfo.html?courseid=1" id="m1">Course 1</a></div>
    <div class="col-md-6"><a href="courseinfo.html?courseid=2" id="m2">Course 2</a></div>
<div>

No JavaScript is needed for that to work.

Then on the receiving page, capture the course id as follows:

var courseid = location.search.match(/[&?]courseid=(.*?)(&|$)/);
if (courseid) courseid = courseid[1]; // get captured group

// this would output "1" if the URL argument was `courseid=1`
console.log(courseid);

Upvotes: 1

Related Questions