Switching between three div elements along with two icons can be done by using toggle functionality

Is there a way to make the icon change back when clicked again without making major changes to the existing code? Looking for suggestions on how to achieve this functionality.

function myFunction() {
  var element = document.getElementById("demo");
  element.classList.toggle("change");
}

function myFunction1() {
  var element = document.getElementById("demo1");
  element.classList.toggle("change");
}

function myFunction2() {
  var element = document.getElementById("demo2");
  element.classList.toggle("change");
}

$('.column1').click(function() {
  var collapsed = $(this).find('i').hasClass('fas fa-check');
  $('.example-class').find('i').removeClass('fas fa-check-circle');
  $('.example-class').find('i').addClass('fas fa-check');
  if (collapsed)
    $(this).find('i').toggleClass('fas fa-check fas fa-check-circle')
});
.change {
  border-color: blue;
  color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<div class="row1">
  <div id="demo" onclick="myFunction()" class="column1">
    <i class="fas fa-check"></i>
    <h2>Learn</h2>
    <p>I'm here to</p>
    <p>look around</p>
  </div>
  <div id="demo1" onclick="myFunction1()" class="column1">
    <i class="fas fa-check"></i>
    <h2>Start</h2>
    <p>I want to find my</p>
    <p>first help desk</p>
  </div>
  <div id="demo2" onclick="myFunction2()" class="column1 clk">
    <i class="fas fa-check"></i>
    <h2>Switch</h2>
    <p>I'm interested in</p>
    <p>swtiching help desks</p>
  </div>
</div>

Answer №1

Streamlined Approach Using jQuery

$('.column1').click(function(){
  $(this).addClass('active').siblings().removeClass('active');
});

No need for additional functions or IDs, just utilize a common class

$('.column1').click(function(){
  $(this).addClass('active').siblings().removeClass('active');
});
/* Helpful CSS */

.column1.active{
  color:blue;
  border: 1px solid blue;
 
}
.fs5::before{
  content:'\f00c';
  font-family: "Font Awesome 5 Free"; 
  font-weight: 900; 
  
}
.active .fs5::before{
  content:'\f058';
  font-family: "Font Awesome 5 Free"; 
  font-weight: 900;   
}
/* Additional Random CSS */

.column1 {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
    padding: 0 5px 
}
.column1 * {
    margin-right: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<div class="row1">
  <div class="column1">
    <span class="fs5"></span>
    <h2>Learn</h2>
    <p>I'm here to</p>
    <p>look around</p>
  </div>
  <div class="column1 active">
    <span class="fs5"></span>
    <h2>Start</h2>
    <p>I want to find my</p>
    <p>first help desk</p>
  </div>
  <div class="column1">
    <span class="fs5"></span>
    <h2>Switch</h2>
    <p>I'm interested in</p>
    <p>swtiching help desks</p>
  </div>
</div>

Answer №2

function updateIcon(element) {
  // Toggle the class on main element
  element.classList.toggle("change");
  // Toggle both check and circle check classes
  element.querySelector('i').classList.toggle('fa-check')
  element.querySelector('i').classList.toggle('fa-check-circle')
}
.change {
  border-color: blue;
  color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<div class="row1">
  <div id="demo" onclick="updateIcon(this)" class="column1">
    <i class="fas fa-check"></i>
    <h2>Learn</h2>
    <p>I'm here to</p>
    <p>look around</p>
  </div>
  <div id="demo1" onclick="updateIcon(this)" class="column1">
    <i class="fas fa-check"></i>
    <h2>Start</h2>
    <p>I want to find my</p>
    <p>first help desk</p>
  </div>
  <div id="demo2" onclick="updateIcon(this)" class="column1 clk">
    <i class="fas fa-check"></i>
    <h2>Switch</h2>
    <p>I'm interested in</p>
    <p>swtiching help desks</p>
  </div>
</div>

Answer №3

Do you find this modification helpful? I updated your click(function(){});.

function myFunction() {
  var element = document.getElementById("demo");
  element.classList.toggle("change");
  
}

function myFunction1() {
  var element = document.getElementById("demo1");
  element.classList.toggle("change");
}

function myFunction2() {
  var element = document.getElementById("demo2");
  element.classList.toggle("change");
}

$('.column1').click(function() {
  var collapsed = $(this).find('i').hasClass('fas fa-check');
  if (collapsed)
    $(this).find('i').toggleClass('fas fa-check fas fa-check-circle')
    
    if(!collapsed)
    $(this).find('i').toggleClass('fas fa-check fas fa-check-circle')

});
.change {
  border-color: blue;
  color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<div class="row1">
  <div id="demo" onclick="myFunction()" class="column1">
    <i class="fas fa-check"></i>
    <h2>Learn</h2>
    <p>I'm here to</p>
    <p>look around</p>
  </div>
  <div id="demo1" onclick="myFunction1()" class="column1">
    <i class="fas fa-check"></i>
    <h2>Start</h2>
    <p>I want to find my</p>
    <p>first help desk</p>
  </div>
  <div id="demo2" onclick="myFunction2()" class="column1 clk">
    <i class="fas fa-check"></i>
    <h2>Switch</h2>
    <p>I'm interested in</p>
    <p>swtiching help desks</p>
  </div>
</div>

Answer №4

Here's a great suggestion for you. Have you heard of alpin.js? It can simplify things for you.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"
      integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ=="
      crossorigin="anonymous" referrerpolicy="no-referrer"/>
<script src="https://cdn.jsdelivr.net/gh/alpinejs/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="23424f534a4d466355110d5b0d5b">[email protected]</a>/dist/alpine.min.js"
        defer></script>

<div class="row1" x-data="sampleData">
    <template x-for="item in items">
        <div id="demo" @click="check($event, item)" class="column1"
             :class="{change:item.checked}">
            <i class="fas"
               :class="item.checked?'fa-check-circle':'fa-check'"></i>
            <h2 x-text="item.title"></h2>
            <p x-text="item.line1"></p>
            <p x-text="item.line2"></p>
        </div>
    </template>
</div>

<style>
    .change {
        border-color: blue;
        color: blue;
    }
</style>

<script>
window.sampleData = {
    items: [
        {
            title: 'Lean',
            line1: 'I am here to',
            line2:'look arround',
            checked: false
        },
        {
            title: 'Start',
            line1: 'I want to find my',
            line2: 'first help desk',
            checked: false
        },
        {
            title: 'Switch',
            line1: 'I\'m interested in',
            line2: 'swtiching help desks',
            checked: false
        },
    ],
    check(e, item) {
        item.checked = !item.checked
    }
}

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

Working with both Javascript and jQuery code within a single HTML file

I recently created a website and on one of the pages, I added some jQuery elements like a start button and progress bar. However, when I tried to implement a JavaScript timer on the same page by adding the script into the header, the jQuery elements stoppe ...

Repeatedly triggering the Jquery Dialog Event

When I open a calendar plugin in jquery dialog, I encounter a recurring issue. Every time I close and reopen the dialog, my calendar event onDayClick triggers multiple times – twice, thrice, and so on. <div id="show_calendar"> <div class="c ...

Seeking additional information on the keydown event in JavaScript and how it is used with jQuery

I'm currently working with jQuery and have the following code snippet: $("#someTextInputID").keydown(function(event){ console.log(event.keyCode); console.log("input_box.val(): "+input_box.val()); console.log("input_box.val( ...

How can you alter the background color of a Material UI select component when it is selected?

I am attempting to modify the background color of a select element from material ui when it is selected. To help illustrate, I have provided an image that displays how it looks when not selected and selected: Select Currently, there is a large gray backgr ...

Every character entered in JSP should trigger an instant retrieval of the corresponding string in the servlet

Having a JSP file that contains a text field: <form action="someServlet" method=post> <input type ="text" name="user" id="uname"> <button type="submit" id="submit">Submit</button> </form> When typing each letter in the JSP, ...

How can I convert this code into a JSON structure?

I have a code snippet that I need to convert into JSON format. The goal is to send the data in JSON format and then display it in a table. Can anyone assist me in making this conversion? Below is the code from index.php <html> <head> ...

How can you implement a resource response approach in Express.js using an API?

As a newcomer in my journey with expressjs, I'm currently exploring its functionalities. In my controller, I've structured the response as follows: .... res.json({ 'data': { 'user': { 'id': us ...

What is the process for obtaining the hash of every hyperlink?

I'm currently working on implementing an active link state based on scroll position for each section. My goal is to extract the hash value from the link. The issue I'm facing is that when I run the line 'console.log($(this).eq(i).hash);&ap ...

Using SVG files in NextJS

I'm encountering an issue while trying to import an SVG file in a NextJS project. The error message I keep getting is: ./assets/aboutimg.svg 1:0 Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type, ...

Using Jquery and css to toggle and display active menu when clicked

I am trying to create a jQuery dropdown menu similar to the Facebook notification menu. However, I am encountering an issue with the JavaScript code. Here is my JSFiddle example. The problem arises when I click on the menu; it opens with an icon, similar ...

Initiate an AJAX request within an existing AJAX request

On one of my pages, page A, I have a form that passes parameters to a script using AJAX. The results are loaded into div B on the same page. This setup is functioning properly. Now, I want to add another form in div B that will pass parameters to a differe ...

What is the best way to line up my columns when they are split between groups of three and two?

I am having trouble aligning my columns in the way I want. The image shows that some tables have 3 columns while others have 2, and I would like to align the blue with the blue and the red with the red as shown in the picture: https://i.stack.imgur.com/1bL ...

Differences between ajax.actionlink replace and replacewithWhen it comes

Within my ASP.NET-MVC application, I am utilizing Ajax.ActionLink in a view and have opted for InsertionMode.Replace. However, I recently came across the ReplaceWith option. Can anyone clarify the distinction between the two? Does one offer a more comprehe ...

Issue with ellipsis not functioning correctly on dynamic placeholders when they are in focus

When I focus on my dynamic placeholder input, the text-overflow: ellipsis property is lost for some reason. However, it is regained when blurred. Can anyone explain why this is happening? If you want to experiment with it, I have set up a stackblitz: htt ...

Submit the image to the server independently from the form

Currently, I am faced with an issue while working on image upload functionality in my React app using Node and Express for the backend. Within my React component, I have a form containing an input type file and a submit button. My goal is to first upload t ...

Concealing option value based on ng-if conditions in AngularJS: A guide

I am designing an Input form with two input fields that need to be compared and values displayed if a certain condition is met. The input fields are: <td class="td_label"><label>Client Age :</label></td> <td class="td_input"> ...

combining HTML and CSS for perfect alignment

I'm having trouble trying to align an image and some text side by side. Below is the code that includes an image and text (Name and Age), but they are not aligning properly even after using float: left. Can anyone help me with this? Thank you. < ...

Dealing with functions that may not consistently return a promise

When dealing with a situation where a function does not always return a promise, how can it be best handled? The complexity of my current code prevents me from providing a detailed explanation, but essentially, the issue involves checking a condition and t ...

Improving Java Performance by frequently replacing one String with another

Currently, I am developing an HttpServlet extension (plugin) for a CMS that is responsible for filtering the HTML response. Within my method filterResponse, I retrieve the requested text/html as a String, which is one of three parameters. The main task a ...

Challenges with the jPages jQuery Plugin

Encountering issues with the implementation of jPages? Wanting to incorporate pagination on a table using jPages and looking to replicate the row by row fadeTo effect observed in the demo, but facing some challenges: Using border-collapsed causes the bac ...