0

I wanted to change the value of my onclick, I tried this but it doesn't work. Any help?

<a href='#' id='social' onClick="">click</a>
document.getElementById("social").onclick = "open_new_window('https://twitter.com/share?url=https%3A%2F%2F"+url+"&amp;via=iguestblogger&amp;text="+title+"');";

NOTE: url, title and open_new_window() are already defined and work fine.

4 Answers 4

1

Instead of changing the value of onclick attribute, just bind the event.

document.getElementById("social").onclick = function() {
  open_new_window('https://twitter.com/share?url=https%3A%2F%2F'+url+'&amp;via=iguestblogger&amp;text='+title);
};
1
  • Hmmm - Not only did I fix the quote but I return false to stop the click from following the href AND I encode the title
    – mplungjan
    Aug 20, 2012 at 12:06
0
document.getElementById("social").onclick = function(){open_new_window('https://twitter.com/share?url=https%3A%2F%2F"+url+"&amp;via=iguestblogger&amp;text="+title+"');};
0

Assuming url and title and function open_new_window was already defined earlier - also watch your quotes

<a href='#' id='social' >click</a>
<script>
document.getElementById("social").onclick = function()
  open_new_window("https://twitter.com/share?url=https%3A%2F%2F"+url+"&amp;via=iguestblogger&amp;text="+encodeURI(title));
  return false;
}
</script>
-1
document.getElementById("social").onclick = open_new_window('https://twitter.com/share?url=https%3A%2F%2F"+url+"&amp;via=iguestblogger&amp;text="+title+"');
2
  • In your code, open_new_window is called before the assignment, and its result is written to the onclick attribute. So, 1) open_new_window is unconditionally executed before the onclick changes (probably, during the page loading), not when the user clicks on the specific link; 2) Clicking on link will cause a javascript error, as open_new_window return value is probably not a function.
    – penartur
    Aug 20, 2012 at 8:16
  • Compare element.onclick = alert('Javascript has been processed'); and element.onclick = function () { alert('Element has been clicked'); };.
    – penartur
    Aug 20, 2012 at 8:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.