Change the class upon clicking the element

Looking to create a function that toggles classes on elements when specific links are clicked. For example, clicking on link 1 should add the "active" class to the red element, while clicking on link 2 should do the same for the pink element, and so forth. My javascript skills are limited, and I've only been able to apply the active class to the links themselves, not the corresponding elements.

$(".trigger").click(function(){
    $('.trigger').removeClass('checked') 
    $(this).addClass('checked') 
 })
.main{
    position: relative;
    width: 500px;
    height: 500px;
}

.basic{
    width: 300px;
    height: 300px;
    position: absolute;
    right: 0;
}

.red {
    background-color: red;
}
.pink {
    background-color: pink;
    
}
.blue{
    background-color: blue;
   
}
.green {
    background-color: green;
   
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="trigger">Link 1</a>
  <a href="#" class="trigger">Link 2</a>
  <a href="#" class="trigger">Link 3</a>
  <a href="#" class="trigger">Link 4</a>

    <div class="main">
        <div class="red basic"></div>
        <div class="pink basic"></div>
        <div class="blue basic"></div>
        <div class="green basic"></div>
    </div>

Answer №1

When the position: absolute property is applied to your basic class, it stacks the children on top of each other. This means that setting any of them to active will not visually change anything. I have removed this property so you can view each element individually. Feel free to style your elements as desired.

To facilitate styling based on a specific element, I've introduced a custom attribute called data-target-class. Using jQuery's attr method, I have retrieved this value into a variable. Subsequently, jQuery's child selector is utilized to remove the active class from all children and then add it back to the specific target element.

Lastly, an active class has been defined which adds a box shadow around the active element for better visibility.

If there are still uncertainties, feel free to leave a comment and I'll work on providing further clarification for you.

$(".trigger").click(function() {
  $('.trigger').removeClass('checked');
  $(this).addClass('checked');
  const target = $(this).attr('data-target-class');
  $(".main > .basic").removeClass('active');
  $(".main > ."+target).addClass('active');
})
.main {
  position: relative;
  width: 500px;
  height: 500px;
  margin-top:2rem;
}

.basic {
  width: 20px;
  height: 20px;
  /*position: absolute;*/
  right: 0;
  margin:1rem;
}

.red {
  background-color: red;
}

.pink {
  background-color: pink;
}

.blue {
  background-color: blue;
}

.green {
  background-color: green;
}

.active {
  box-shadow: 0px 0px 16px 5px #00FF0F;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="trigger" data-target-class="red">Link 1</a>
<a href="#" class="trigger" data-target-class="pink">Link 2</a>
<a href="#" class="trigger" data-target-class="blue">Link 3</a>
<a href="#" class="trigger" data-target-class="green">Link 4</a>

<div class="main">
  <div class="red basic"></div>
  <div class="pink basic"></div>
  <div class="blue basic"></div>
  <div class="green basic"></div>
</div>

Answer №2

<html>

<head>
  <style>
    .container {
      position: relative;
      width: 600px;
      height: 600px;
    }

    .box {
      width: 350px;
      height: 350px;
      position: absolute;
    }

    .yellow {
      background-color: yellow;
    }

    .orange {
      background-color: orange;

    }

    .purple {
      background-color: purple;

    }

    .teal {
      background-color: teal;

    }
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    $(document).ready(function () {
      $(".btn").click(function () {
        $('.btn').removeClass('active')
        $(this).addClass('active')
        let text = $(this).text().trim();
        $(".box").css("z-index", "0")
        if (text == "Tab 1") {
          $(".yellow").eq(0).css("z-index", "10");
        }
        else if (text == "Tab 2") {
          $(".orange").eq(0).css("z-index", "10");
        }
        else if (text == "Tab 3") {
          $(".purple").eq(0).css("z-index", "10");
        }
        else if (text == "Tab 4") {
          $(".teal").eq(0).css("z-index", "10");
        }
      })
    });
  </script>
</head>

<body>
  <a href="#" class="btn">Tab 1</a>
  <a href="#" class="btn">Tab 2</a>
  <a href="#" class="btn">Tab 3</a>
  <a href="#" class="btn">Tab 4</a>

  <div class="container">
    <div class="yellow box"></div>
    <div class="orange box"></div>
    <div class="purple box"></div>
    <div class="teal box"></div>
  </div>
</body>

</html>

Answer №3

Give this a shot:

 $(document).ready(function(){
            $(".trigger1").click(function(){
                $('.basic:eq(0)').toggle();
            });
            $(".trigger2").click(function(){
                $('.basic:eq(1)').toggle();
            });
            $(".trigger3").click(function(){
                $('.basic:eq(2)').toggle();
            });
            $(".trigger4").click(function(){
                $('.basic:eq(3)').toggle();
            });
        })
.main{
    position: relative;
    width: 500px;
    height: 500px;
}

.basic{
    width: 300px;
    height: 300px;
     
    right: 0;
     
}

.red {
    background-color: red;
}
.pink {
    background-color: pink;
    
}
.blue{
    background-color: blue;
   
}
.green {
    background-color: green;
   
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="trigger1">Link 1</a>
  <a href="#" class="trigger2">Link 2</a>
  <a href="#" class="trigger3">Link 3</a>
  <a href="#" class="trigger4">Link 4</a>

    <div class="main">
        <div class="red basic"></div>
        <div class="pink basic"></div>
        <div class="blue basic"></div>
        <div class="green basic"></div>
    </div>

 

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

What steps should be taken to populate a grid row if a certain div element is not present?

I am currently using tailwindcss and have this specific HTML code snippet: REPL: https://play.tailwindcss.com/L8McFjGBVC <div class="grid grid-cols-12"> <div class="col-span-4 bg-red-300">1</div> <div class=&qu ...

Calling components may result in a race condition

I have integrated 2 components into my "App" that work together seamlessly. The first component is responsible for resolving the external IP address to a geographical location by making 2 axios.get calls and then passing them back to App.vue using emit. F ...

What are the Functions of Ctrl-K on Stack Overflow?

I'm intrigued by how to incorporate the Ctrl+K (code sample) feature for code. For example: public static void main(String args[]){ System.out.println.out("welcome"); } Is there a way to nicely format this? Do we need any specific package to ...

Include new items in the li tag using JavaScript

Hello, I am looking to dynamically add elements to an LI element when a link is clicked. I have successfully added elements to a DIV using the following code snippet: I came across a similar question on Which "href" value should I use for JavaScript links ...

The 1and1 Server is experiencing a 500 internal error when using Ajax and jQuery .Load() functions, but accessing the URL directly seems to

Currently, I am utilizing a jQuery .load() function to enable infinite scrolling in a CakePHP web application. Below is the snippet of Javascript code: $("#post_container").append('<div class="batch row" style="display:none;"></div>&apos ...

Exploring Next.js: Leveraging fetch to retrieve data in getServerSideProps and passing it to the client via query parameters

I'm utilizing a getServerSideProps function on the directory page. pages/catalog/index.js export async function getServerSideProps(ctx) { const response = await fetch( `http://someDomen.com/api/ipro/catalog?${ctx?.query?.page ? `page=${ctx.quer ...

Vue js: Automatically assign alternate text to images that are not found

Currently, I am in the process of developing a website that features a variety of products, each with its own unique image. For binding the image URL to the source attribute, I use the following code snippet: <img :src="product.ImageUrl"/> In case ...

Including a hyperlink in VUE Bootstrap for seamless user navigation

Why does this always drive me crazy? I'm determined to include an external link () and an image(enter image description here) on my portfolio page within the title of the project. main.js { id: 18, url: 'single-portfolio. ...

What is the difference in performance between using element.class { ... } compared to just .class { ... } in CSS?

Is there any impact on performance when specifying div.class or p.class instead of just .class if a certain class will only be used on divs or paragraphs? ...

Refreshing a div using Php and ajax at specific intervals

Can I load the div values automatically when the page loads along with after a time interval? How can I achieve this? <script type="text/javascript> $(document).ready(function() { setInterval(function(){ $("#Te ...

Is it possible to display an element within a designated div using jQuery?

I am working with an element that I want to display in the middle of the page using a for cycle so it can be populated with the correct information. This particular element is hidden but should appear on hover. However, it doesn't look very aesthetica ...

Creating a glowing shimmer using vanilla JavaScript

After successfully creating the Shimmer Loading Effect in my code, I encountered a hurdle when trying to implement it. The effect is visible during the initial render, but I struggle with utilizing it effectively. The text content from my HTML file does no ...

Set the text alignment to the left/start inside a div contained within a Material UI Box

Trying to figure out how to make the error handling ui of this field look like another field's error handling ui. Note that in the second example, the error text is aligned to the left. How can I achieve this alignment without considering text color ...

Encountering an issue: Module """ not located at webpackMissingModule

I'm facing an issue while trying to webpack my express application. Specifically, I encounter the following problem whenever I attempt to access the / page: Encountering Error: Cannot find module "." at webpackMissingModule Below is a snippet of c ...

Separating a variable within a Twitch bot: techniques and tips

I am working on setting up a feature in my Twitch bot where it can respond to the command !test [var]. For example, if someone types !test @jeff, the bot would reply with hello @jeff. Currently, I am using tmi. client.on('chat', function(channe ...

Trigger the jQuery function once the external URL loaded via AJAX is fully loaded

Currently, I am in the process of developing a hybrid mobile app for Android and I am relatively new to this technology. I have two functions in jQuery, A and B. Function A is responsible for making an AJAX request to retrieve data from 4 external PHP fi ...

Searching for corresponding items in multi-dimensional arrays using Javascript

For my project in Javascript, I am facing the challenge of matching entire arrays. In this scenario, I have a userInput array and my goal is to locate a similar array within a multi-dimensional array and display the match. var t1 = [0,0,0]; var t2 = [1,0, ...

Triggering an Angular AJAX call by selecting a radio button

I am currently working on implementing a CRUD functionality in my app for the admin console. My tech stack includes MongoDB, Spring, Bootstrap, and Angular. The interface consists of a list of radio buttons on the left side containing names of collections ...

How do I execute a Next.js script that utilizes `fs` and `sharp` during development with Webpack?

I'm working on creating a basic GIFPlayer that displays a GIF when the play button is clicked, and shows a PNG otherwise: <img className="w-full h-full" src={isPlaying ? gifPath : imgPath} alt={pic.alt} /> Since I only have a GIF file ...

Intermittent AJAX 403 Forbidden errors occur from time to time

My goal here is to validate whether a username is already taken in real-time as the user types, triggering an AJAX call on keyup event to check if it's available. If the username is taken, the input field will be highlighted in red. However, I've ...