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

Customizing the style of react-select is essential for creating a unique and visually appealing user experience

I am looking to maintain the visual style of my input fields to match that of a react-select component. I have been advised to use styled-components, yet I am uncertain about which styles need to be adjusted in order to achieve the desired outcome. Ideally ...

Tips on preserving CSS modifications made in Chrome Developer Tools Inspector to .vue file

Currently, I am in the process of setting up a new workflow where my goal is to streamline my work by using the Chrome DevTools Inspector to save any CSS changes directly to my .vue file. While the DevTools Workspaces feature can achieve this, it involves ...

What is the best way to send FormData from a React JS axios post request to a Node server?

I am facing an issue where the form data is not reaching the node server even though it shows in the network payload at the time of request. Below are the snippets from different files involved in the process. let formData = new FormData(); // fo ...

Creating a Rest API URL in Vue.js by extracting form values

I just finished coding this Vue component: <template> <div> <h2>Search User By ID</h2> <input v-model="userId" type="number" placeholder="modify me" /> <br /> <p v-if="userId.length != 0"> ...

Retrieve the database value for the chosen name and then add that name to a different table

I am working on a dropdown feature that fetches categories from a database and displays the selected category price in a textfield. For example, when 'web development' is selected, the price ($12) will display in the textfield. Below is the cod ...

The $mdSticky feature in AngularJS Material seems to be malfunctioning

It's been a challenge for me to get the md-toolbar to stay in the top position. I decided to create a custom directive using the $mdSticky service in AngularJS. var app=angular.module('app',['ngMaterial']); app.controller(&apos ...

What are the steps to compile Sencha Touch using sencha-touch.jsb3?

I've been working on modifying the bundled sencha-touch.jsb3 file in an effort to decrease the size of the framework code. Here's what I've done so far: First, I downloaded the Sencha SDK Tools from I then made edits to SenchaTouch/sen ...

"Utilize Javascript to upload a picture and showcase it on your website

<!DOCTYPE html> <html> <head> <title>Unique Webpage!</title> <meta charset=utf-8 />                       <link rel="stylesheet" href="styles/customcss.css" /> <script src="j ...

Selectize Fails to Populate Options Using Ajax

ExpressJS is the platform I am using to develop a management dashboard for a community project. Right now, my main concern is integrating a modal that allows users to add new games to a database. Although I am able to fetch data remotely, I am facing diffi ...

Struggling with CSS on your website and need some help?

Working on a website project with my own design, I ran into an issue regarding the positioning of the menu style. Describing this problem can be challenging, so let's start by looking at some images. What it should look like: Current appearance ...

Invoke the button's click event by the name property

One could have an HTML button defined as, <input type="button" id="btnSubmit" name="btnName" class="btnclass" value="Click Me" /> To trigger a jQuery button click event based on the id property, one ...

What could be the reason for a jQuery script failing to execute when included in a PHP include statement from a different PHP page?

I'm currently working with javascript and php to manage cookies across different pages. On one page, I have a script that sets a value in a cookie variable and I want to retrieve that value on another page. Let's say the first page is named page1 ...

How can I extract and display chosen values from multiple dropdown menus in designated text boxes based on their unique identifiers?

A website for evaluating car values is in the works, using a combination of PHP, MYSQL, JQUERY, and JavaScript. The database includes 3 tables: Table "car_make": id make 1 BMW Table "model": model_id model_name make_id 1 M3 1 Table "ca ...

What are some effective CSS styles that can be used to illustrate the concept of "loading . . ."?

I've been leveraging the power of blockUI successfully, but now I'm faced with the challenge of dynamically loading a table row. My research indicates that blockUI may not be compatible with HTML table rows. My idea is to use: jquery.AddClass(" ...

What exactly is the purpose of editing a host file?

After reviewing this repository, an automatic message pops up: Don't forget to modify your host file 127.0.0.1 * http://localhost:3001 What exactly does that entail? ...

Select your vehicle from the drop-down menu

Seeking assistance with a Javascript drop-down selector for vehicle make, model, and year. The goal is to dynamically generate a link based on the user's selections. I'm struggling with implementing the year selection without replacing the model. ...

Designing tables and image galleries using HTML, CSS, and jQuery: A guide

How can I easily transform tabular data into thumbnails with the click of a button? I need a 2-view system that switches between table and thumbnail views without including image thumbnails. I welcome any creative suggestions! :) Examples: ...

Sorting rows by words and numbers in JavaScript explained

Hello, I'm a beginner and I need help sorting the table rows in the following table. I also want to attach an onclick listener to the header after it is displayed. ID Name Inventory Volume 1 Rachel Data is not enough 2 Ross 100 3 Monica 1 ...

Making Bootstrap Carousel images slide seamlessly

Can someone help me with implementing Bootstrap carousel slides that display gif short clips when transitioning to the next page? I've searched through Bootstrap documentation and Stack Overflow for solutions, but I can't seem to get the slide to ...

Utilize Jquery's "find" function to showcase an image

I am attempting to showcase an image using jQuery. I have a function that accepts ID and PATH as parameters. The ID indicates the section (each section is an HTML page that loads upon user action). Additionally, there is a text area where I am displaying t ...