-1

I have this html codes:

<span name="value1"></span>
<span name="value2"></span>

I'm trying to make the page scroll to these sections every time the page's URL with the span loads.

Example: htttp://site.com/index.html#value1

If value1 is selected, there is a scroll when the page is opened.

I'm trying this code :

$(document).ready(function() {  
        var target = $(this.hash);  
        if (target.length == 0) target = $('[name="' + this.hash.substr(1) + '"]');  
        if (target.length == 0) target = $('html');  
        $('html, body').animate({ scrollTop: target.offset().top }, 700);  
        return false;  
});

I can do this with id but I want to do it with name attr.

Metin
  • 1
  • You can use a mixture of [querySelector](https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelector) and [scrollIntoView](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView). Select the element by attribute value then scroll to it. `document.querySelector("span[name='value1']").scrollIntoView()` – D M Jan 14 '21 at 20:26
  • https://stackoverflow.com/questions/3163615/how-to-scroll-html-page-to-given-anchor Can be adapted to your needs I think. There are even up-to-date solutions without jQuery! – Emilio Grisolía Jan 14 '21 at 20:27

2 Answers2

0

May I kindly suggest to consider a solution without JavaScript?

<a name="value1"></a><span name="value1"></span>

This will use the browser's default behavior to go to the respective section upon loading the page.


Should the identification of the element be the issue, you may try traditional JS:

if (target.length == 0) {
    target = document.getElementsByName(window.location.hash.substr(1))[0];
}
BurninLeo
  • 4,240
  • 4
  • 39
  • 56
0

Your JavaScript code looks like it should work for both id and name attributes, and since it works for ids, I think maybe the problem is one of two possible issues in your HTML:

1. When you're trying to scroll to an element by name, do you also have an element with that id on the page?

As you can see from these lines in your code:

var target = $(this.hash);  
if (target.length == 0) target = $('[name="' + this.hash.substr(1) + '"]'); 

The script will only look for an element with name={hash} if an element with id={hash} is not found.

2. Your tags are invalid HTML

I don't think this technically should prevent the script from working the way you want, but it's probably useful to know anyway. Only certain elements are supposed to have a name attribute, as you can see from this other SO question.

I believe what you want here is <a name="value...">, using the Anchor tag for one of its original intended uses.

Dharman
  • 30,962
  • 25
  • 85
  • 135
bmdev
  • 386
  • 1
  • 7