user3468711
user3468711

Reputation: 143

setting href value to javascript variable on click

I am trying to get the href value passed to a variable when the user clicks on the link from a particular class. This is what I have right now.

$(document).on('click',"a.show-notes",function{
    var $url = $(this).attr("href");
)};

This is not working for me though, and no value is being passed to the variable. I have also tried something like this, with no luck...

$("a.show-notes").on('click',function(){
    var $url = $(this).attr("href");
)};

I imagine that there is something obvious here that I am missing, but I've been starring at it for so long that my mind is fried.

Upvotes: 0

Views: 802

Answers (3)

Wilmer
Wilmer

Reputation: 2511

You have some syntax errors:

$(document).on('click',"a.show-notes",function(){
    var $url = $(this).attr("href");         //^missing parenthesis
    alert($url);
});
//^bad closing

Note: Also the $variable name convention is normally used only for jquery elements like:

var $element = $("li");

Upvotes: 1

scrodde
scrodde

Reputation: 106

Ensure you're setting those hooks after the DOM has loaded and those elements exist. Wrap them inside a $(document).ready function like this:

$(document).ready(function() {
  $("a.show-notes").on('click',function(){
    var url = $(this).attr("href");
    console.log(url);
  });
});

Upvotes: 3

Alexandre FILLATRE
Alexandre FILLATRE

Reputation: 1327

Try

$('a.show-notes').click(function(){
    var $url = $(this).attr('href');
});

The variable $url variable can be named however you like (url, myLink, etc.) but it is only visible inside the click() function. If you want to use it outside, create the variable before the click() function, and set it inside.

Upvotes: 0

Related Questions