Utilize hashchange event to display specific div elements

I have several hidden divs on my webpage. Users can select jobs by clicking on links (such as "#job8"). I am attempting to use the hashchange function in my script to check the URL for a specific hash and then show the corresponding div.

Below is an example of one of the divs:

<div class="job-details" id="job8" data-jobid="8">
    <p>Job 8</p>        
</div>

This is the script I am using:

$(document).ready(function(){

        $('.job-details').hide();
});

$(window).bind('hashchange', function() {

        if (location.hash.substring(0,4) == "#job"){
            var jobID = location.hash.substring(0);

            $('.job-details').hide();
            $('[data-jobid="' + jobID + '"]').show();
          }


});

Answer №1

Here is your code:

var jobID = location.hash.substring(0);

Currently, this assigns '#' to the variable jobID. This may not be the intended behavior. Perhaps what you actually want is:

var jobID = location.hash.substring(4);

Answer №2

Is it necessary to utilize the hashchange event? If not, consider the example provided below, which includes a FIDDLE:

<nav>
  <a href="#job1" data-rel="job1">Job 1</a>
  <a href="#job2" data-rel="job2">Job 2</a>
  <a href="#job3" data-rel="job3">Job 3</a>
</nav>

<div class="job-details" id="job1">
  <p>Job 1</p>        
</div>
<div class="job-details" id="job2">
  <p>Job 2</p>        
</div>
<div class="job-details" id="job3">
  <p>Job 3</p>        
</div>

.job-details {
  position: absolute;
  width: 400px;
  height: 200px;
  border: 1px solid #ddd;
  display: none;
}

$(function() {
  $('nav a').click(function() {
    $('.job-details').fadeOut(400);
    $('#'+$(this).data('rel')).fadeIn(400);
  });    
});

Answer №3

Palpatim is absolutely correct, this snippet will get the job done:

let identifier = window.location.hash.substring(4);

If you'd like to see it in action, here's a link to the jsfiddle: http://jsfiddle.net/Cc9dL/

Answer №4

jQuery hashchange

After some modifications in the get/set jobid, your function is now functioning correctly.

Upon receiving location.hash as #job8, you can directly utilize this as an id selector.

$(window).bind('hashchange', function() {
     if (location.hash.substring(0,4) == "#job"){
         var jobID = location.hash;
         $('.job-details').hide();
         $(jobID).show();
     }
});

Try it out on fiddle

Updated :

$(window).bind('hashchange', function() {
     if (location.hash.substring(0,4) == "#job"){
        var jobID = location.hash.substring(4);
        $('.job-details').hide();
        $('div[data-jobid="' + jobID + '"]').show();
     }
}); 

Give it a go on Fiddle

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

Refresh the webpage content by making multiple Ajax requests that rely on the responses from the previous requests

I am facing a challenge where I need to dynamically update the content of a webpage with data fetched from external PHP scripts in a specific sequence. The webpage contains multiple divs where I intend to display data retrieved through a PHP script called ...

The Facebook Checkbox plugin stays out of sight

I have been trying to implement the Facebook Checkbox Plugin on a test page following the documentation. However, I am facing an issue where the checkbox remains hidden and does not render. You can check out my test page here. After going through several ...

Curved corners when an image is located on the border

Looking to create a basic website with React using Reactstrap and Bootstrap. I'm trying to add a custom border-radius to my Cards, but facing an issue where the image inside the Card is overlapping the container on the upper side. Is there a CSS prope ...

What is the best way to load additional data based on categories instead of all at once?

Is there a way to load additional data based on specific categories without loading all the data at once? For instance, if I select number 2 and receive results, how can I then load more data that only corresponds to the number 2 filter? Thank you in advan ...

Error Message: Upon pressing the login button, an uncaught TypeError occurs indicating that the property 'element' cannot be read because it

I encountered an issue Uncaught TypeError: Cannot read property 'element' of undefined whenever I click on the login button in my Ionic2 and Angular2 application. I have checked for uninitialized variables or functions but could not find any. ...

HTML and CSS: Aligning Text on the Left and Image on the Right - A Guide to Positioning Elements

Just starting out with HTML and CSS, I've run into some issues while writing my code. My goal is to have Text (on the left middle part) and image (on the right middle part) displayed side by side A responsive design that stacks the text on top of t ...

"ajax:success" being triggered twice

When using jquery_ujs to send a simple post request, I noticed that the callback function bound to the "ajax:success" event is being executed twice for each successful post. I did some research and found this question on Stack Overflow which addresses a s ...

Find all the members belonging to a specific role in a Discord guild using discord.js client and store them in an array

I am attempting to create an array containing all users with a specific role, yet I keep encountering the following error message: TypeError: Cannot read property 'members' of undefined This is the code snippet that I am currently utilizing: var ...

Laravel Ajax 419 Error Occurring in Production Environment, Yet Absent in Local Development, with No Trace in /storage/logs/laravel

I encountered a 419 Error code while submitting my AJAX request in my project. This error is related to the CSRF Token not being passed or invalid. Recently, I implemented a "maintenance mode" on my project that restricts access to the front end by displa ...

Avoiding the backslash in JavaScript

<script type="text/javascript"> console.log(#Fileurl#); jQuery.ajax({ url: "http://xyz:8800/aaa/bbb/ccc", type:'POST', dataType: 'JSON', data:{"file":"#Fileurl#"}, success: function ...

Animate the menu as you scroll

I am attempting to create a jQuery top menu that adjusts its height based on the window scroll position. Using $(selector).css("height", "value") works fine, but when I try to animate it, it doesn't behave correctly. Here is my code. Thank you for you ...

What is the best way to supply arguments to a generic handler function?

How can I send parameters to a generic handler in Asp.net using JavaScript/jQuery? I am working on a jQuery plugin called ajaxfileupload that utilizes a generic Handler. I need to pass certain arguments from the page using jQuery or JavaScript, such as Dy ...

Using the ES6 filter method to iterate through a double nested array of objects

Struggling with filtering a nested array of objects and specifically stuck at the filter part. Any idea on how to eliminate one of the marks? this.state = { data: [ { id: 1, name: "Main", subs: [ { id: "jay", ...

What is the best way to transfer a "require" object to Jade in Node.js?

I have developed a node module that includes a simple JavaScript file. My goal is to utilize this JavaScript function within my jade file. In music.js, I am importing the "myplayer" module: var keystone = require('keystone'); exports = module.ex ...

Invoke a functional component when a button is clicked in a React application

I have a functional component that includes a button. My goal is to trigger another functional component when this button is clicked. Upon clicking the Submit button, the Preview button appears. When the user clicks on the preview button, it should call t ...

Is it possible to concatenate a variable within the path of another variable?

I am currently exploring the option of using a package.json to organize variables in different 'categories,' as shown below: "servers": { "category1": { "modrole": "Moderator" }, "category2": { "modrole": "bot owner" ...

I'm curious about the outcomes of the JavaScript test. Could someone provide an explanation

Recently, I was in the process of writing a blog post discussing the importance of checking for the existence of jQuery elements before attaching event handlers. To illustrate this, I quickly created a jsfiddle example here. What puzzles me is that the re ...

Automate CSS slideshow playback using JavaScript

Using only CSS, I created a basic slideshow where the margin of the element changes upon radio button click to display the desired slide. You can view the functionality in the code snippet below. Additionally, I implemented auto play for this slideshow usi ...

Error: The variable "xxxx" is undefined. Attempting to assign a PHP variable to JavaScript

I have a URL mapped like this: xxx/app/reset.php?token=fc832c73b6695a782cb1040b48a1ac2e6c33aaf2&action=reset After assigning it as follows: $token = $_GET['token']; $token_ = "_".$token; I store it in a JavaScript variable like so: var ...

Having trouble making the swing effect trigger on mouseover but not on page load

I am trying to achieve a swinging effect on mouseover only, not on page load. Below is the JS code I have: (function swing() { var ang = 20, dAng = 10, ddAng = .5, dir = 1, box = document.getElementById("box"); (function setAng(ang){ ...