0

I want to redirect my page to an anchor of itself when an element with a certain class is clicked. This is what I thought would work:

$(function()
{
  $('.paginacion').click(function()
  {
    var $this = $(location).attr('href');
    $this += '#nav';
    $(location).attr('href', $this);
  });
});

However, I can see how the wanted location is produced in the URL, but a snap later it's gone and it doesn't go to the anchor. What's wrong? Note that I'm pretty dumb with javascrip and jQuery.

dabadaba
  • 9,064
  • 21
  • 85
  • 155
  • Why not just use `location.href = $this`? (I would also suggest $url is a better variable name, so as not to get confused with `this`) – stuartd Dec 28 '13 at 00:11
  • No. Location is not an element. `attr` will not work. –  Feb 19 '18 at 06:00

3 Answers3

1

If you're looking for the equivalent of assigning to window.location.href, you need to use prop, not attr:

$(location).prop('href', $this);

.prop() vs .attr()

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Could you not write:

$(function () {
  $('.paginacion').click(function()
  {
    var $this = window.location.href;
    $this += '#nav';
    window.location.href = $this;
  });
});
Lucas
  • 16,930
  • 31
  • 110
  • 182
0

You don't understand how jQuery works. .prop and .attr are for DOM elements, not objects like location. I don't really understand the point of your code to be completely honest with you, as when .pagination is clicked it will just add #nav to the location. I'm assuming you want to get the attribute of the clicked element and go to that instead of just adding #nav, as that would be pointless.

$(function() {
      $('.pagination').click(function()
        //spelling error | (paginacion => pagination)
        {
            location.href=$(this).attr("href");
        });
      });

Or if you just want to append #nav to the location, then use this.

    $(function() {
          $('.pagination').click(function()
            //spelling error | (paginacion => pagination)
            {
                location.href+="#nav";
            });
          });

If you could, please elaborate and add to your question.