If the URL hash matches the ID of a specific div, then take action on the div's child element

Imagine I have the following HTML structure:

<div class=".blog-item-holder">
<div id="AAAA"><div class="inner">AAAA</div></div>
<div id="BBBB"><div class="inner">BBBB</div></div>
<div id="CCCC"><div class="inner">CCCC</div></div> 
<div id="DDDD"><div class="inner">DDDD</div></div>
</div>

Now, each URL will be structured like this:

example.com/page/#AAAA
and
example.com/page/#BBBB
and
example.com/page/#CCCC
and
example.com/page/#DDDD

The goal is to have the div#BBBB .inner with a black background when someone visits a specific page (example.com/page/#BBBB), and the same treatment for other links (for CCCC, DDDD, etc).

Here is the JavaScript code I have so far:

if(window.location.hash) {
var hash = window.location.hash.substring(1),
    boxes = [];

$('.blog-item-holder > div').each(function(){
    if ($(this).attr('id') == hash) {
        $(this).children('div').css("background-color:#000000;");
    }
});
}

Unfortunately, it seems that the script is not working as intended.

Answer №1

It is recommended to use the proper syntax for applying CSS using .css():

$(this).children('div').css("background-color","#000000");

or:

$(this).children('div').css({"background-color":"#000000"});

rather than using:

$(this).children('div').css("background-color:#000000;");

Answer №2

The :target pseudo-class is meant for situations like this. You don't need to search for window.location.hash using a script - just use the following CSS and it will be applied automatically:

:target > .inner {
    background-color: #000000;
}

If you have to use jQuery for compatibility with older browsers that don't support :target in CSS, you can still incorporate it in a jQuery selector if you're using version 1.9 or later (check here for more information). Just make sure to correct your .css() parameter:

$(':target > .inner').css("background-color", "#000000");

Once again, there's no need to access window.location.hash unless you require the hash fragment for other purposes. This single statement can replace the entire if block.

Answer №3

It's essential to remember not to assign CSS properties through JQuery; instead, utilize the key, value method in .css() for proper assignment.

Prioritize debugging to identify the specific values associated with the hash variable.

if(window.location.hash) {
var hash = window.location.hash.substring(1),
    elements = [];

$('.post-container').find('.content').each(function(){
    if ($(this).parent().attr('id') == hash) {
        $(this).css("color","#FF0000");
    }
});
}

Answer №4

Success is guaranteed!

$(window).on('hashchange',function(){
  var _element = $(location.hash).children('.inner');
  _element.css('backgroundColor', '#000');
})

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

Is jQuery each function always sorting the elements?

In my JavaScript code, I have a specific object: var list = {134 : "A",140 : "B",131 : "C"} To iterate over the object, I use this code snippet: jQuery.each(list, function(key, value) { console.log(key + " - " + value); }); The expected output should ...

In Node.js, I encountered an issue where req.body was returning as undefined, despite the fact that when I logged req, I could

I am having trouble logging the req.body to the console in my Twilio text app. When I try console.log(req), the body and its contents show up, but it says that the body is undefined when I try to log it on its own. Any help would be greatly appreciated. ...

Show the most recent image from a folder in real-time

Looking for a solution to automatically display the latest image from a folder without refreshing the page? Check out this code snippet that achieves just that: <?php foreach (glob('/home/pi/camera/*.jpg') as $f) { $list[] = $f; } sort( ...

Enhancing webpage design by dynamically changing borders and headers using JavaScript

I have implemented a fixed positioning for the table headers using the following code: onScroll={() => { document.querySelector('thead').style.transform = `translate(0,${this.scrollRef.scrollTop}px)`; }} However, when I scroll the ta ...

The text following a table is spilling into the table because it is too big to fit within the designated div

I've been searching for a solution to this issue (it's a common problem), but nothing I've attempted has resolved it. Currently, I am using jQuery Mobile. Below is the code snippet in question: <div style="width:100%; height:220px;"> ...

What is the process for getting the input value when a key is released?

My goal is to capture the actual value or text from an input field and store it in a variable. However, when I use the console to check the output, it shows me a number indicator that increments each time I type something. <input id="usp-custom-3" ty ...

The function "getElementsByClassName" in Javascript is malfunctioning

I have redesigned my website by implementing an interactive feature where users can click on a tree image to remove it and replace it with a number using JavaScript. Initially, I targeted the specific tree with the following code: document.getElementById( ...

When trying to serialize elements from a form loaded by Firefox using AJAX, encountering difficulties due to

Visit the live version of this at . When prompted for a formId, input BroadRunTrack2013. Follow by adding an item to cart and entering player name information (you can use random data for now). Select the Runner's Hat, choose color/size, specify quant ...

Show information from a JSON response using Ajax and present it on a jQuery dialog within an MVC3 view

I currently have an ActionResult method within a Controller which retrieves a row of data (such as id, name, city, etc) from the database based on the provided ID [HttpPost] public ActionResult Get(Guid Id) { Ref imp = ReadRepository.G ...

I am experiencing issues with the functionality of my ajax form request

I am trying to display an alert message on my page but it doesn't seem to be working. Below is the code from my view: $.ajax({ url :"<?php echo base_url();? >booking/dispatch_challan/DispatchChallanController/createDispatchChallan", ...

What is the proper way to structure a URL in JSON output?

When utilizing JSON output in my project, I encountered the following result: {"short_url":"http:\/\/urlhere\/fb\/37xzk"} However, the desired output should be formatted as follows: { "short_url":"http: //urlhere/fb/37xzk" } ...

The CSS focus-within and hover properties are not functioning as expected

How can I make the search tags visible (the buttons above the text input field) when the search bar below them is clicked? I've tried using :hover, :focus, and :focus-within, but none of them seem to be working. Can someone help me figure out the issu ...

Why is the Ajax call not selecting the image in the ASP.NET form?

I've been working on a project using asp.net core and I encountered an issue with sending an ajax request to the controller. Specifically, my ajax function is causing me some trouble when it comes to uploading images/files. Currently, whenever a user ...

Loop through a nested array and output the playerId, playerName, and playerCategory for each player

update 3: After thorough debugging, I finally found the solution and it has been provided below. let values = { "sportsEntitties": [{ "sportsEntityId": 30085585, "sportsEntityName": "490349903434903490", "sportsEntityStartDate": "7878 ...

As the background image shifts, it gradually grows in size

I'm attempting to create an interesting visual effect where a background image moves horizontally and loops seamlessly, creating the illusion of an infinite loop of images. Using only HTML and CSS, I've run into an issue where the background ima ...

A method for automatically refreshing a webpage once it switches between specific resolutions

On my page www.redpeppermedia.in/tc24_beta/, it functions well at a resolution of over 980px. However, when the resolution is brought down to 768px, the CSS and media queries alter the layout. But upon refreshing the page at 768px, everything corrects itse ...

javascript conceal other sections upon hovering

There are 4 list items (<li>) that I want to use as triggers for linked images. In this project, I am using vanilla JavaScript as jQuery is not allowed. Below is the code snippet: var children = document.querySelectorAll('#resistorContent > ...

Showing how an iframe can adjust its height to 100% within a div element

Currently, I have a player status script implemented on our Minecraft Server. This script displays the server name, IP address, and the heads of the players currently online. The setup includes two div boxes for the status box: one outer box to fix its pos ...

Using AJAX to Capture PHP Error Responses

I have implemented a form where users can upload profile pictures and see live validation feedback without refreshing the page. I am currently using AJAX for this functionality, but it seems that the requests are not reaching the PHP file. Also, after subm ...

When attempting to render HTML containing multiple CSS classes within a JSON request parameter, the styles are not being applied as expected

In my API, I'm dealing with a JSON request parameter that includes an HTML string. This HTML string references CSS styles from a separate .css file. However, when an HTML element has two CSS classes assigned to it, neither of the classes' styles ...