Ways to individually select and activate several HTML elements with matching classes, and then apply styles to a different div featuring multiple classes using Jquery or JavaScript

Within my webpage, I have created a section with three links. Clicking on each link reveals specific content (content 1, content 2, and content 3). The issue arises when I have two identical sections (Section 1 and Section 2) and clicking on a link displays the content in both sections simultaneously.

I am seeking assistance either through JQuery or vanilla JavaScript to resolve this dilemma. My current implementation is not optimal, so any improvement suggestions are welcome. Below is the Codepen link for reference:

<a href="https://codepen.io/dan-zins/pen/mdammed">codepen</a>

Here are some screenshot references:

https://i.sstatic.net/XUOIH.png

https://i.sstatic.net/AtqWC.png

https://i.sstatic.net/rCABh.png

https://i.sstatic.net/CAA5m.png

I have explored various sites looking for a solution, including using data-id and $(this) in the onclick function, but haven't been successful in resolving my specific issue.

Answer №1

Implementing a quick solution by scoping the change to the parent element of the clicked item.

Note that there are more efficient methods explained below.

$('.link-1').on('click', function () {
    var parent = $(this).closest(".section");
    parent.find('.content-1').css({ 'display': 'block' });
    parent.find('.content-2').css({ 'display': 'none' });
    parent.find('.content-3').css({ 'display': 'none' });
});

// More similar functions here...

Although reducing duplicate code, this method may not be ideal for real-world applications due to specificity issues with the display property.

$('.section a').on('click', function () {
    var target = $(this).data("target");
    $(this).closest(".section").find('.content').removeClass("display");
    $("."+target).addClass("display");
});

Exploring an alternative approach using the href attribute to determine the target, promoting semantic structure and potentially boosting SEO.

// Event delegation example
$(".section").on("click",function(e){
  if(e.target.matches("a")){
    $(this).find(".content").removeClass("display");
    $(e.target.getAttribute("href")).addClass("display");
}
});

This strategy could almost function without JavaScript, relying primarily on CSS; however, limitations with multiple :target selectors restrict displaying content in more than one section simultaneously.

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

Retrieving data from Node.js within an Angular application

I am currently working on retrieving data from MongoDB and displaying it on my website. However, I am facing an issue in sending the entire fetched object to a specific port (the response) so that I can retrieve it from Angular. I also need to know how to ...

Issue with jquery's .load() and getScript functions

Earlier today, I encountered an issue with a .load() function being called in a script. I managed to solve the problem using .getScript(), but now I'm facing a major issue - the function is being executed multiple times. You can find the full code a ...

Java - RESTful API endpoint that serves images when available and JSON data when images are not available

I am currently working on incorporating a mobile front-end using the Ionic Framework along with the $cordovaFileTransfer plugin. My focus is on fetching and uploading a person's Profile Photo. Uploading the photo is functioning properly, but I am enco ...

How can I delay the execution of "onAuthStateChanged" until "currentUser.updateProfile" has completed?

Currently facing an issue with registering users in my Vue app. When a user registers, I need to trigger the updateProfile function to add more user data. However, the problem arises when the onAuthStateChanged function in my main.js is executed before the ...

Sort elements based on the chosen option in the select component

Here's a link to my app on Codesandbox https://codesandbox.io/s/filter-search-gxidc?file=/src/App.js which consists of only one component, app.js Within data.js, I have an array of objects: export const data = [ { currencies: [{ code: "AFN ...

Pattern for reactive forms in Internet Explorer 11

I'm currently working with this form setup: this.form = this.formbuilder.group({ weight: [weight, [Validators.pattern('^(0|[1-9][0-9]*)$')]], height: [height, [Validators.pattern('^(0|[1-9][0-9]*)$')]] }); Conta ...

Access a website from a different domain and include JavaScript code dynamically

My goal is to develop a mobile-friendly web app that loads a website from a different domain and applies JavaScript code to adjust the layout. I have heard that JavaScript typically does not allow cross-domain requests, so I'm wondering how this could ...

How is Inheritance Utilizing Computed Values?

The article I'm currently reading discusses the concept of "Inheritance Uses Computed Values." According to the chapter, computed values are essential for inherited values such as font sizes that utilize lengths. These values are relative to other ele ...

Having trouble changing a state from a class component to a function component in React

I've been updating my React projects by converting all my classes to functions. However, I encountered an issue where ESLint is reporting a parsing error in my code. Oddly enough, if I remove just one line, the error disappears. Here's the snippe ...

Stylish mobile navigation styles with CSS

Hey there, I appreciate any help you can provide. I'm having trouble figuring out the right CSS code to modify the colors of my Mobile Menu only... I'd like to change the placeholder text as well as the text and background of the drop-down menu ...

The submission of the form using AJAX is currently experiencing issues

My current issue involves ajax not functioning as intended. I have a form that is being submitted through ajax to my php file for the purpose of updating my database. The database update is successful, but there seems to be a problem with the ajax function ...

What is the best way to showcase a list on a toggle-able dropdown menu, divided into groups of 5

I needed to incorporate data from my database into my navbar dropdown. Below is the JSON data: { "1": [{ "id": 1, "moduleId": "1", "dropdownModuleName": "NL", "isDeleted": null, "createdBy": "1", "updat ...

Received a notification after submitting an HTML form

<html> <body> <form action="" method="GET> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> <?php if( $ ...

The Bootstrap navbar appears to extend beyond the content on the page

I am new to using Bootstrap. I have encountered an issue with the navbar on my website. The navbar appears to be longer than the screen size and the right button is being overlapped by the right side of the window. Unfortunately, I am unable to scroll the ...

Jsdelivr does not automatically synchronize with updates made to GitHub commits

Check out this JavaScript file I have stored on GitHub. // Remember to define the function before setup() and call it under draw() function pointCoord() { stroke(255,0,0); line(mouseX,0, mouseX, height); line(0,mouseY, width, mouseY); ...

My HTML table is not printing at full width

Seeking assistance with creating a printable calendar using an HTML table. The calendar prints perfectly on a Mac, but when attempted on Windows in all browsers, it adds a 3" margin at the top regardless of CSS print settings. The client requires the cal ...

Exploring the power of Django Haystack search within your HTML pages

Just had a thought: is it possible to search directly in an HTML file, ignoring the tags if desired? I couldn't find a quick answer on Google. To explain further, we have a crawler that returns the HTML of a page. If I want to search the content of t ...

Attempting to send an array of files to a Meteor function

When calling a method within a submit button event, the code looks like this: 'submit #form': function(event, tmpl){ var files = null; if(event.target.fileInput) files = event.target.fileInput.files; console.log(f); Met ...

Next.JS is having trouble importing the URL class from the 'url' module in Node

Recently, while developing with next.js and webpack 5, I encountered an issue where my URL class import stopped working unexpectedly. Upon running npm run build, the following error message appeared: Attempted import error: 'URL' is not export ...

The 4.6 version of Bootstrap introduces a popover feature that remains visible even when the element reaches its boundaries, stopping scrolling in

I am facing an issue with popover display using Bootstrap 4.6 Here is a basic example: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/html"> <head> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email- ...