Community
Community

Reputation: 143

jQuery .attr() returning first(wrong) value?

Basicly I made a function that opens a page in a container #page when you click on .menu now the problem I'm having that it always shows the first .menu data-open="url/url.html".

Let me explain this with the code:

I have 2 list items:

<li class="menu" data-open="pages/home.html"><a href="#"><div class="wrap">HOME</div></a></li>
<li class="menu" data-open="pages/services.html"><a href="#"><div class="wrap">SERVICES</div></a></li>

and I have .click function like this:

$("nav ul li.menu").click(function () {
    var url = $("nav ul li.menu").attr("data-open");
    console.log(url);
    loadPage(url)
});

Now the url ALWAYS returns from the FIRST list item no matter if I click on SERVICES.

Here's a GIF:

enter image description here

Upvotes: 1

Views: 563

Answers (1)

Dave
Dave

Reputation: 10924

You need to reference the item that was clicked. Use:

var url = $(this).attr("data-open");

Instead of:

var url = $("nav ul li.menu").attr("data-open");

Upvotes: 9

Related Questions