I am currently trying to make an html link that will add elements (specifically, drop down menus) to the current page when you click it. Since I am adding all the elements to the page using JavaScript, I'm not sure how to set up the link to call a function rather than go to a different page. I've seen people set the href attribute to the function they want, so I tried that and it didn't work. I've also seen a way that involves using onclick and making the link follow the onclick, not go to a different page.

In summary, how do you create/edit a link (from javascript) to make it use a javascript function rather than go to a different page?

This is what I have currently (that concerns the link):

var link = document.createElement('a');
eval("link.setAttribute('href', 'javascript:addHours(" + dayDiv + ")');");

Recommended Answers

All 4 Replies

I think its more reliable to use the onclick event handler.

<!-- The goal is to create the following HTML. -->
<a href="#" onclick="addHours('dayDiv'); return false;">Add Hours</a>
var link = document.createElement("a");
link.setAttribute("href", "#");
link.onclick = function() { addHours('dayDiv'); return false; };
link.innerHTML = "Add Hours";

Hope this helps.

I believe that is the solution I'm looking for, but when I implement it, I can't get anything to work. When I click the link nothing happens. I'm not sure if this is because the function I wrote isn't working or if the link is still incorrect.

Is your addHours function implemented? Does it throw an error?
You are going to have to post your code--can't help you otherwise.

The function wasn't working. Problem now solved. Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.