When the div is clicked, it changes color and then reverts back to its original color when another

I have encountered an issue where I need to differentiate the div I clicked on in order to avoid confusion, as the pop-up menu on my website will be identical with different links but the same buttons. I have been struggling to find a solution for quite some time now. It is important to note that my site is built on Wordpress. The color of the text is not significant at the moment. Although my code functions properly, I am looking to implement a feature whereby clicking on "juicyplants" changes the color, and then when I click on "leafyplant", the color changes back while "juicyplants" returns to its normal state. By changing colors, I mean altering the existing color schemes. Below is my current code:

HTML:

<div id="clickOne" class="clickDesign">
<h2 class="fs20 nobold">Leafy Plants</h2>
</div>
<div  id="clickTwo" class="clickDesign">
<h2 class="fs20 nobold">Juicy Plants</h2>
</div>
</div>
<div id="leafyPlants">
Leafy Test
</div>
<div id="juicyPlants">
Juicy Test
</div>

CSS:

   #leafyPlants{
        display:none;
        position:absolute;
        top:50px;
    cursor:pointer;
    }

#juicyPlants{
    display:none;
    position:absolute;
    top:50px;
    cursor:pointer;
}

h2 {
    float:left;
    display:block;
    height:40px;
    width:150px;
    cursor:pointer;
}

jQuery:

  $("#clickOne").on('click', function() {
   $("#leafyPlants").fadeIn();
   $("#juicyPlants").fadeOut();
});
$("#clickTwo").on('click', function() {
   $("#leafyPlants").fadeOut();
   $("#juicyPlants").fadeIn();
})

Answer №1

It's advisable to change classes and apply styling:

Check out the jsfiddle demo: http://jsfiddle.net/TrueBlueAussie/Pcn5a/2/#update

$(function () {
    $("#clickOne").on('click', function () {
        $('.clickDesign').removeClass("active");
        $(this).addClass("active");
        $("#leafyPlants").fadeIn();
        $("#juicyPlants").fadeOut();
    });
    $("#clickTwo").on('click', function () {
        $('.clickDesign').removeClass("active");
        $(this).addClass("active");
        $("#leafyPlants").fadeOut();
        $("#juicyPlants").fadeIn();
    })
});

For styling, include the following in your CSS:

.active{
    color: green;
}

Consider data-driven menu systems for more efficient code:

JSFiddle link: http://jsfiddle.net/TrueBlueAussie/Pcn5a/3/

JQuery example:

$(function () {
    $('.clickDesign').on('click', function () {
        var $this = $(this);
        $('.clickDesign').removeClass("active");
        $this.addClass("active");
        // Utilize the id stored in data-target attribute
        $target = $($this.data('target'));
        $(".target").not($target).fadeOut();
        $target.fadeIn();
    });
});

Html (includes data-target attributes)

<div>
    <div id="clickOne" class="clickDesign" data-target="#leafyPlants">
         <h2 class="fs20 nobold">Leafy Plants</h2>

    </div>
    <div id="clickTwo" class="clickDesign" data-target="#juicyPlants">
         <h2 class="fs20 nobold">Juicy Plants</h2>

    </div>
</div>
<div id="leafyPlants" class="target">Leafy Test</div>
<div id="juicyPlants" class="target">Juicy Test</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

You can use jQuery AJAX to submit two forms' data simultaneously in just one submission

I am looking to submit two sets of form data with just one click. <form id="form1"> <input type="text" name="name"> <input type="submit" value="Submit"> </form> <form id=&quo ...

Struggling to grasp the concept of Vue3 style binding

While browsing the Vue website, I came across a particular example that left me puzzled. Inside the <script> section, there is this code: const color = ref('green') function toggleColor() { color.value = color.value === 'green' ...

I am encountering an issue with identifying a directory in Node.js

This is my HTML code <div id="done_work_1" class="logo-slide-track"> </div> <script>$.ajax({ url: "/static/home/done/", success: function (data) { $(data).find("a").attr("href&q ...

jQuery Plugin: Struggling to figure out default settings

Is there a way to set default options for this plugin code? // Utility if ( typeof Object.create !== 'function' ) { object.create = function( obj ) { function F(){}; F.prototype = obj; return new F(); }; } (function( $, window, docu ...

What is the best way to stop an embedded mp4 video from playing when a dynamically generated button is clicked?

After making modifications to the QuickQuiz code found at https://github.com/UrbanInstitute/quick-quiz, I have replaced the img with an embedded mp4 video that loads from a JSON file. Additionally, I switched from using the original SweetAlert library to S ...

Creating an Editor for Input Text Field in HTML: A Step-by-Step Guide

In the vast landscape of JS libraries that can achieve this function, like Trumbowyg and more. However, prior to my rails project displaying that slim version, I need to ensure JavaScript is properly escaped! Therefore, I need to create an editor using o ...

What could be causing the discrepancy in results between the first and second methods?

Implementing Weather Icons: const getWeatherIcon = (iconParameter) => { const icon = `https://openweathermap.org/img/wn/${iconParameter}@2x.png` return <img src={icon} alt={iconParameter} /> } <div className="weathericon"> ...

Angular - Strategies for Handling Observables within a Component

I am new to Angular and recently started learning how to manage state centrally using ngRx. However, I am facing a challenge as I have never used an Observable before. In my code, I have a cart that holds an array of objects. My goal is to iterate over the ...

Hover function not functioning properly

I can't figure out why this hover effect isn't working, there doesn't seem to be a negative z-index or anything like that. At most, it just flashes on hover; .menu{ border-radius: 50%; width: 100px; height: 100px; background: white; box-sha ...

Implementing Dynamic Weight-based Pricing with CodeIgniter and AJAX

My shopping cart website utilizes ajax and Codeigniter to add products without reloading the page. Originally, I displayed a single net weight for each product. However, I recently switched to multiple net weights for the same product. Unfortunately, I am ...

Utilizing the componentDidUpdate method to update the state within the component

I have a scenario where two components are enclosed in a container. One component is retrieving the Id of a publication, while the other is fetching the issue date related to that specific publicationId. When I retrieve an Id, let’s say 100, it successf ...

When attempting to send data to the ServiceStack RESTful service, an error message of 'Access is denied' was received

I created a RESTful service using ServiceStack to send data to a database. It worked perfectly when tested locally. However, after deploying it to a server and running the same jQuery $.ajax call code, I encountered an 'Access is denied' error. I ...

Unable to locate the image file path in React.js

I'm having trouble importing images into my project. Even though I have saved them locally, they cannot be found when I try to import them. import {portfolio} from './portfolio.png' This leads to the error message: "Cannot find module &apos ...

Error loading Azure Active Directory web form: Server returned a 401 status code for the requested resource

I recently made changes to my web site (incorporating a web form and entity framework) to use AAD connection, following the guidance in this insightful blog post. However, I am encountering an issue where scripts and css files are not loading properly. Th ...

Does the Array Splice method always remove an item from the end?

I'm having trouble with deleting an item from an array using Array.splice. It seems to always delete the item from the end instead of where I want it to be removed. I'm working with Vue.js and dynamically adding items to an array, but when I try ...

Should you create an archive - Retain outcomes or retrieve them whenever needed?

I am currently developing a project that allows users to input SQL queries with parameters. These queries will be executed at specified intervals determined by the user (e.g., every 2 hours for 6 months), and the results will be sent to their email address ...

Click event triggering smooth scrolling

I am currently working on implementing a smooth scrolling effect using the React JavaScript library without relying on jQuery. My goal is to ensure that when a user clicks on a link, they are directed to the specific section of the page seamlessly. The f ...

What is the best way to extract information from the response of a fetch request in JavaScript using Express and Node.js

Currently, my script code resides in the index.html file, which I understand is not the ideal location. However, I am in the process of getting it to work before relocating it. readOperaciones(); async function readOperaciones(){ try{ ...

Transforming dynamic tables into JSON format

Whenever a user adds a new row to the dynamic table to input customer information, I require the data to be submitted in JSON format upon clicking the submit button. HTML <table class="table table-bordered table-hover" id="driver"> ...

What is the best way to insert fresh input values into a different element?

click here to view image description I am working with an input element where I take input values and store them in an element. However, I would like to know how to input new values into the next element. Any assistance would be greatly appreciated. Thank ...