Using JavaScript to add a hashtag to a URL

I am interested in creating a website using ajax without compromising its SEO value. My question is: What would happen if I have links on my page like this:

   <a href="http://example.com/cats" id="cats">Cats</a>
   <a href="http://example.com/dogs" id="dogs">Dogs</a>

...when each link is clicked, I want to update the URL in the address bar with a corresponding hashtag. For example, if the "Cats" link is clicked, the current location will be http://example.com/#cats, allowing me to display my ajax content. In cases where JavaScript is disabled or the user is a search engine bot, they should be directed straight to /cats

Answer №1

To modify the location.hash property is a way to update the current anchor identifier without reloading the page. For instance, you can achieve this by:

<a href="http://mysite.com/cats" id="cats" class="ajaxLink">Cats</a>
<a href="http://mysite.com/dogs" id="dogs" class="ajaxLink">Dogs</a>

Following that:

$('.ajaxLink').click(function (e) {
  location.hash = this.id; // extract the id of the clicked link
  e.preventDefault(); // prevent navigating to the URL

  // retrieve content using Ajax...
});​

Answer №3

For security reasons, it's not possible to change the window.location.href in JavaScript without triggering a page reload.

I've heard conflicting information about Google indexing # urls - some say they will be indexed but not treated as individual pages, which may not align with your goals. SEO is also an area where I have limited expertise.

Answer №4

While simplicity is key, if you're looking to streamline or generalize this process, consider using the lightweight plugin jquery.hashTag.js

$('a').hashTag({
    source: function() {
      return $(this).attr('id');
    }
  });

Simply insert this code snippet within your $(document).ready function.

The plugin will take care of the rest for you, such as automatically clicking on the link with the specified id in the hash.

Answer №5

In the discussion, BenMills brought up location.hash as an alternative to location.href, emphasizing that it does not necessitate a page reload.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to get the hang of CSS animation?

Here is a code snippet that I am using: //Code for animating skills on view document.addEventListener("DOMContentLoaded", function(event) { function callback(observations, observer) { observations.forEach(observation => { if (observati ...

Load a form using ajax and submit it using jQuery

For a while now, I have been facing challenges in figuring out what's going wrong with my code. The issue arises when I try to submit a form using jQuery that was loaded through ajax. The form loads perfectly fine within a div after invoking the ajax ...

Jquery onchange event fails to fire

$('#selectclassid').trigger("change"); $('#selectclassid').on('change', function() { }); When trying to manually trigger the onchange event, it does not seem to be firing as expected. Although this format is commonly seen ...

I'm having trouble using Ajax calls in Intel XDK

For my current project, I transitioned from PhoneGap to Intel XDK. Everything seemed to be running smoothly, except for one issue - my Ajax calls were not being processed. I followed the documentation and added the following two lines of code before any ot ...

A guide on selectively removing a value from a javascript object when calling setState in ReactJS

updateDishDetails(id, quantity) { if (quantity !== 0) { this.setState( prevState => ({ bookingFormData: { ...prevState.bookingFormData, dishDetails: { ...prevState.bookingFormData.dishDe ...

Exploring the functionalities of radio buttons and arrays in a Javascript experiment

Currently delving into the world of Javascript and struggling to wrap my head around creating a test using only pure Javascript (no jQuery). The goal is to: Present users with a question and provide radio button options for selection. Allow users to cho ...

Axios mistakenly sending DELETE requests before GET requests

I'm currently developing a Vue.js project that is connected to a Lumen API and everything is functioning smoothly. Within this project, I have implemented a list of students ('Etudiants') that allows users to select and delete a student by ...

I encounter Error 406 and CORS issues when making API calls

I am currently engaged in a project aimed at helping my employer keep track of shipping loads, customers, carriers, and locations. The frontend is built using a react app that enables users to input information regarding loads, customers, etc. On the backe ...

Enabling table row scrolling with keyboard navigation in React

Struggling to figure out how to make my table scroll while navigating through the rows using the onKeyDown event. It seems that the event isn't updating when using the keyboard, even though the highlighting of the selected row with selected is working ...

SignalR error: A type conversion issue has occurred where it is not possible to directly convert a task returning an object to a string

I'm encountering an issue with my C# hub class where the JavaScript code is returning a System.Threading.Tasks.Task instead of a string. I need help modifying the JavaScript method to return an actual string. Below is the hub class: public String ge ...

Utilizing *ngfor in Angular 7 to Group and Display Data

I currently have incoming data structured like this in my Angular application Visit this link to see the data format https://i.stack.imgur.com/jgEIw.png What is the best way to group and sort the data by State and County, and present it in a table as sh ...

Troubleshooting Problems with Ajax File Uploads

Welcome to My Unique HTML Form <center> <form enctype="multipart/form-data"> {{ csrf_field() }} <label class="fileContainer"> <input type="file" id="uploadFile" name="input_upload_file[]" multiple /&g ...

Triggering the Bootstrap modal multiple times with each increment

I am experiencing an issue with Bootstrap Modal where the action fires up multiple times upon clicking. <div id="loginModal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> ... & ...

After receiving a response from an Ajax call, the forms are reloaded

Experimenting with servlet calls through Ajax functionality using a simple program. A form consisting of a text box and a div with some text. The program takes input from the user, replaces the text inside the div tag. The form looks like this: <form& ...

VueJS encountered an insecure XMLHttpRequest endpoint during the request

I am currently working on a project that consists of a VueJs app with a Laravel backend serving as the API. While testing the app locally, everything works smoothly with the Https protocol. However, upon deploying it to the production server, I encountere ...

Local email.js functionality successful, but fails upon deployment alongside React

I have implemented Email.js to create a contact form for a Next.js website. It functions perfectly when tested locally, but encounters issues once deployed. Upon clicking the submit button, the form fails to reset as intended within the sendEmail function. ...

How can one optimize the speed of an image swap using jQuery or JavaScript?

I seem to have encountered a peculiar issue. In my code, I have the following snippet: http://jsfiddle.net/PMnmw/2/ Interestingly, in the jsfiddle example everything runs smoothly. The image swaps occur swiftly and effortlessly. However, when implemented ...

Create a dynamic process that automatically generates a variety of div elements by using attributes from JSON data

Is there a way to organize the fixtures from this data into separate divs based on the matchday attribute? I've tried using Underscore's groupBy function but I'm unsure how to dynamically distribute the data into individual divs for each re ...

Incorporating an external library into a Node.js virtual machine

I'm currently working on a nodejs library that enables users to write and execute their own JS code. Here is an example: var MyJournal = Yurnell.newJournal(); module.exports = function(deployer) { MyJournal.description = "my first description& ...

problems encountered while trying to increment ng-click function in Angular JS and Ionic

I'm currently working on developing a quiz using Angular JS and Ionic Framework. However, I've encountered an issue: The "Continue" button is not functioning as expected when clicked (using ng-click) to move to the next question. &l ...