Javascript a href hash

Add and Change URL Hash (#) in JavaScript Without Reloading

You can add hash value to a URL using JavaScript to navigate a user from one section to another without reloading the page. You can also change the existing URL hash.

JavaScript has the location.hash property that can add or change the hash value in the URL. The history API can set a hash to the current URL using the pushState() method in JavaScript. If the URL is a string, the URL() constructor can attach the value to the string.

You use this technique to move one section to another on a web page. When we create a table of contents, we set the id of different sections as the hash value.

In this article, I will show 3 methods to add or change the hash value of a URL in JavaScript without reloading the page.

Add JavaScript URL Hash Using location.hash Property

The hash property from the location object can return the existing hash value from the current URL in a browser. You can also check for the hash (#) value in a URL using JavaScript and set a new value to change the hash.

The location object contains information about the current URL. That’s why we can modify the current URL using the properties and methods of this object.

location.hash = 'reviews'; // https://example.com#reviews 

I am adding «reviews» to the URL as a hash value by setting it to the location.hash property. It is a very easy process.

If your current URL is «https://example.com» in the browser, this line of code will attach «#reviews» at the end of that URL. Like, https://example.com/#reviews

Add and Change URL Hash (#) in JavaScript Without Reloading

This property not only adds value but also can get the existing hash value from a URL in JavaScript. We can extract it from the current URL using location.hash property.

Change URL Hash With History API in JavaScript

JavaScript history API has several methods to add hash value to a URL. They also add value to the current URL in a web browser.

Methods like pushState() and replaceState() can change the URL without reloading the page in JavaScript. When we change the URL, we will attach the hash value to it.

history.pushState('', '', '#reviews'); 

This line of code will add the «#reviews» to the current URL. I am using pushState() method from the history object. You can also use the replaceState() method.

Читайте также:  Php если значение не кратно

But in that case, you can’t go back to the previous page by pressing the back button in your browser. Both of them will set the hash value.

Update Hash Value Using URL() Constructor

Sometimes we might have a URL string that contains a hash value. We want to add the hash value to that string. It is very easy to add something to a string.

You can use the string concatenation technique to join a piece of string to another string.

const url = 'https://example.com'; const newURL = `$#reviews`; // https://example.com/#reviews 

I am adding » #reviews » to the url string to get a new URL with the hash value. I am using the template literal syntax in JavaScript.

You can also do it using the URL() constructor function in JavaScript. It accepts an URL string and returns an object. This object will contain information about that string.

const url = 'https://example.com'; const urlObj = new URL(url); urlObj.hash = '#reviews'; console.log(urlObj.href); // https://example.com/#reviews 

I am passing the url string to the constructor and it returns the object. This object has a hash property that can add a hash value to the URL.

Now, you can access the updated URL from the urlObj.href property. You can redirect to the new URL in JavaScript to get the content.

It might look like more work compared to the previous technique. But it is more helpful than the string concatenation when we try to change the existing hash value.

We can easily add something at the end of a string. But to change something, at first we have to remove that part. Then we can attach a new string.

const url = 'https://example.com/#reviews'; const urlObj = new URL(url); urlObj.hash = '#comments'; console.log(urlObj.href); // https://example.com/#comments 

As you can see, you have to follow the same process to change the hash value using URL() constructor. It is a very easy and simple way to modify the URL hash value.

Conclusion

There are many use cases of the hash value in a URL. We can take our users from one section to another without reloading the page. In this way, a user doesn’t have to load the page again and again.

That’s why it is important to know how to work with URL hash in JavaScript. You can also remove a hash from the URL using JavaScript.

Читайте также:  Php очистить пустые элементы массива

You have learned 3 methods in this article. Now, you can use any one of them to add and change the hash value from a URL using JavaScript.

Источник

window . location

location — это объект хранящийся в window , который позволяет получать информацию о текущем адресе страницы и менять его с помощью функций или обновления полей объекта.

Пример

Скопировать ссылку «Пример» Скопировано

С помощью location мы можем получить текущий адрес:

 // если выполнить этот скрипт на текущей странице доки в консолиconsole.log(window.location.href)// 'https://doka.guide/js/window-location/' // если выполнить этот скрипт на текущей странице доки в консоли console.log(window.location.href) // 'https://doka.guide/js/window-location/'      

Обновление текущей страницы можно произвести с помощью reload ( ) . Этот метод делает то же самое, что и кнопка «Обновить» в браузере:

 window.location.reload() window.location.reload()      

С помощью replace ( ) можно сделать клиентский редирект, это приведёт к мгновенному переходу по адресу, указанному при вызове метода:

 window.location.replace('https://doka.guide/') window.location.replace('https://doka.guide/')      

Как понять

Скопировать ссылку «Как понять» Скопировано

Для навигации по сайту мы используем адреса и параметры страницы. window . location содержит набор свойств и методов, чтобы удобно получать адрес и управлять им.

Как пишется

Скопировать ссылку «Как пишется» Скопировано

Свойства

Скопировать ссылку «Свойства» Скопировано

Ссылка, на которой обозначены все свойства window.location

href – полное представление адреса. Можно сказать, что это зеркало того, что находится в адресной строке браузера в данный момент. Если записать значение в это свойство, то произойдёт обновление адреса и редирект на новый адрес.

Остальные свойства — это кусочки location . href . Они нужны, чтобы удобно получать каждый из них отдельно, а не вытаскивать их руками из полной строки адреса.

 console.log(window.location.href)// отобразит текущий адресwindow.location.href = 'https://example.com'// сделает переход по указанному адресу console.log(window.location.href) // отобразит текущий адрес window.location.href = 'https://example.com' // сделает переход по указанному адресу      

protocol содержит текущий протокол по которому открыта страница. Чаще всего там будет https и http .

host содержит значение хоста из ссылки. Хост включает в себя название текущего домена и порта.

hostname — частичка с доменом из свойства host , не включает в себя порт.

port — вторая составляющая значения host , содержит только номер порта. Если порт не указан в явном виде, то значением свойства будет пустая строка » .

origin включает в себя путь, начиная с protocol и заканчивая port .

search содержит параметры в формате ключ = значение разделённые & . Если параметров нет, то значением будет пустая строка.

Читайте также:  Приложение баз данных php

hash — якорная ссылка включая символ # . Она находится в самом конце пути и отвечает за навигацию между размеченными на странице элементами с помощью установки атрибута id на тегах. Эта часть URL не передаётся на сервер. Если параметров нет, то значением будет пустая строка.

 window.location.hash = 'в-работе'// проскролит страницу до элемента с `id="в-работе"` если такой присутствует на страницеconsole.log(window.location.hash)// напечатает якорь window.location.hash = 'в-работе' // проскролит страницу до элемента с `id="в-работе"` если такой присутствует на странице console.log(window.location.hash) // напечатает якорь      

pathname – репрезентация текущего пути на сайте. Если текущий урл не содержит путь, то значением будет корневой путь » / » .

Например, значения window . location . pathname в зависимости от адреса:

  • https : / / doka . guide / js / window — location / → /js / window — location / .
  • https : / / doka . guide → / .

Методы

Скопировать ссылку «Методы» Скопировано

assign ( новый _ путь ) – метод вызывает переход на страницу, переданную в аргументах. После перехода на страницу пользователь может вернуться на страницу, с которой произошёл переход, с помощью браузерной кнопки назад.

replace ( новый _ путь ) аналогичен методу assign ( ) , но адрес страницы с которой был вызван этот метод не будет сохранён в истории браузера. При попытке вернуться назад пользователь будет отправлен на страницу предшествующую той, с которой произошёл переход.

reload ( ) перезагружает текущую страницу.

to String ( ) приводит адрес страницы к строке. Возвращает то же самое значение, что и location . href .

Источник

Window location.hash

The location.hash property sets or returns the anchor part of a URL, including the hash sign (#).

Note

When location.hash is used to set the anchor part, do not include the hash sign (#).

Syntax

Parameters

Return Value

Browser Support

location.hash is supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью