0

How to load a new URL depending on which div was clicked. Every div has its own URL for loading (in my implementation divs are blog pages).

My JQuery: & My html:

$('.postWraper').click(() => {
        window.location = $(this).find('h3').find('a').attr('href');
        return false;
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="postWraper">
    <h3 class="postTitleH3">
        <a href="blog/first-page" class="postTitle">
            <%= post.postTitle %>
        </a>
    </h3>
</div>
<div class="postWraper">
    <h3 class="postTitleH3">
        <a href="blog/second-page" class="postTitle">
            <%= post.postTitle %>
        </a>
    </h3>
</div>

When I clicked on first or second div it's allways redirect me to first URL. I can't understand why. Please help!

shas
  • 703
  • 2
  • 8
  • 31
Darovskiy
  • 7
  • 1
  • 3

2 Answers2

6

The meaning of this is changed because you're using arrow function as the event handler. Change that to a regular function:

$('.postWraper').click(function() {
    window.location = $(this).find('h3').find('a').attr('href');
    return false;
});
31piy
  • 23,323
  • 6
  • 47
  • 67
1

You don't necessarily need to change the arrow function. You can still make it work by passing the event object in click event and using e.target.href; to get the href value:

$('.postWraper').click((e) => {
  window.location = e.target.href;
  return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="postWraper" id="<%= post.id %>">
    <h3 class="postTitleH3">
        <a href="blog/first-page" class="postTitle">
            Some title
        </a>
    </h3>
</div>
<div class="postWraper">
    <h3 class="postTitleH3">
        <a href="blog/second-page" class="postTitle">
            Some title
        </a>
    </h3>
</div>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62