I prefer to disable the toggle feature if the target remains unchanged

My goal is to create a step-by-step ordering system using the data-id="x" attribute to determine which content should be visible when selected.

I want to make sure that if two elements have the same data-id, clicking on one will deselect the other. Any suggestions on how to achieve this?

Here's my current code:

$('li').on('click',function(e) {
  e.preventDefault();
  $(this).closest('section').nextAll('section').find('li').removeClass('selected');
  $(this).siblings('li').removeClass('selected').end().toggleClass('selected');
  var $target = $('#'+$(this).attr('data-id'));
  if ($target.length) {
    $(this).closest('section').nextAll('section').find('.step').not($target).removeClass('active');
    $target.toggleClass('active'); 
  } else {
    console.log('do something else to end this thing');
  }
})

Here is a link to my JSFiddle with examples and the above code.

Can anyone provide an example of how this code will work along with a brief explanation? Thank you.

Answer №1

To apply the CSS property pointer-events: none; to elements with the .selected class, you can use the following jQuery code:

$('li').on('click',function(e) {
  
if($(this).hasClass('selected')){
return false;
} else {
e.preventDefault();
$(this).closest('section').nextAll('section').find('li').removeClass('selected');
$(this).siblings('li').removeClass('selected').end().addClass('selected');
var $target = $('#'+$(this).attr('data-id'));
if ($target.length) {
$(this).closest('section').nextAll('section').find('.step').not($target).removeClass('active');
$target.addClass('active'); 
} else {
console.log('do something else to end this thing');
}
}
})
h1 {
  font-size: 20px;
}
.step {
  display: none;
}
.active {
  display: block;
}
.selected {
  background: #27ae60 !important;
  color: #fff !important;
}
ul {
  padding:0;
}
li {
  list-style: none;
}
.bananas {
  padding: 20px;
  color: #7f8c8d;
  background: #ecf0f1;
  display: inline-block;
  border-radius: 10px;
  cursor: pointer;
  width: 25%;
  text-align: center;
  font-size: 16px;
  font-weight: 700;
}
.hi {
  color: #e74c3c;
  border-bottom: 2px dotted #e74c3c;
}
h1 {
  margin-top: 30px;
  margin-bottom: 30px;
}

#same_target {
  margin-top: 30px;
  background: #9b59b6;
  padding: 20px;
  color: #fff;
}

#same_target p {
  margin-bottom:0;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>


<div class="container">
  <section>
    <h1>First step, please choose something</h1>
    <ul>
        <li class="bananas" data-id="one">
          Sprite
        </li>
        <li class="bananas" data-id="two">
          King Kong
        </li>
        <li class="bananas" data-id="three">
          Astronauts
        </li>
      </ul>
  </section>

  <section>
    <div id="one" class="step">
    <h1>Second step for <span class="hi">Sprite</span> - choose another</h1>
      <ul>
        <li class="bananas" data-id="same_target">
          McDonalds
        </li>
        <li class="bananas" data-id="same_target">
          Burger King
        </li>
        <li class="bananas" data-id="same_target">
          Tim Hortons
        </li>
      </ul>
    </div>

    <div id="two" class="step">
      <h1>Second step for <span class="hi">King Kong</span> - choose another</h1>
      <ul>
        <li class="bananas" data-id="same_target">
          McDonalds
        </li>
        <li class="bananas" data-id="same_target">
          Burger King
        </li>
        <li class="bananas" data-id="same_target">
          Tim Hortons
        </li>
      </ul>
    </div>

    <div id="three" class="step">
      <h1>Second step for <span class="hi">Astronauts</span> - choose another</h1>
      <ul>
        <li class="bananas" data-id="same_target">
          McDonalds
        </li>
        <li class="bananas" data-id="same_target">
          Burger King
        </li>
        <li class="bananas" data-id="same_target">
          Tim Hortons
        </li>
      </ul>
    </div>
  </section>

  <section>
    <div id="same_target" class="step">
      <p class="fml">
        Now select another brand and watch this content toggle, even when the target is the same.
      </p>
    </div>
  </section>
</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

Unable to modify the bar's color using the .css document

Below is the JavaScript code being used: var marginEducation = {top: 20, right: 30, bottom: 40, left: 300}, widthEducation = 1000, heightEducation = 460; const svgEducation = d3.select("#Education") .append("svg") .attr("w ...

How can you easily ensure your React web app is responsive?

As I delve into building a web app using reactjs, one particular challenge I encounter is ensuring its responsiveness. An issue arises when the browser size changes, causing my components to overlap and lose alignment. Is there an easy solution to preven ...

Tips for retrieving multiple data outputs from an ajax success function

Within my project, I have two separate JavaScript files named myJs1.js and myJs2.js. One of the methods in myJs1.js is invoking a method from myJs2.js. My goal is to retrieve the values r1 and r2 into the results (within myJs1.js). I attempted to achiev ...

Commitment to provide the outcome of the second promise in case the first one encounters

I am trying to handle the scenario where I need to return the value of a second promise if the first one (value in cache) fails. Below is my code snippet, but I'm encountering an issue where 'resolve' is not defined. exports.getConfig = fu ...

Issue encountered while deploying on vercel: TypeError - Trying to access properties of undefined (specifically 'and')

Encountered this issue during deployment on Vercel. Npm run build did not show any errors. Configuration : "node": "18", "next": "^14.0.0", "next-transpile-modules": "^9.1.0", An error occurred d ...

Using AngularJS to invoke the ng-required directive and trigger a function

Is it possible to make the required value dependent on a function? Something similar to this? I need to achieve this in order to dynamically change the required attribute for form inputs... HTML: Name: <input type="text" ng-model="user.name" ng-r ...

Transform a numerical variable into a string data type

I am faced with a situation where I have a variable named val which is currently set to the number 5. Now, my goal is to update the value of val so that it becomes a string containing the character "5". Could someone guide me on how to achieve this? ...

Identifying the completion of loading a HTML page using an object tag

I am trying to load an HTML page using an object tag, and once the page is fully downloaded, I want to display something. I have attempted the following approach, but it is not working: document.querySelector(".obj_excel").addEventListener("load", funct ...

Initiating SignalR multiple instances

SignalR is causing me trouble because I am calling .start() multiple times. Below is my jQuery code that currently works: var signalR = $.connection.chat; var signIn = function() { $.connection.hub.start().done(function () { signalR.server.sign ...

The CSS file seems to be ineffective when building Vue in production

In my Vue project, I am using a single file component with a chart module. In order to customize the styles of the chart module's CSS, I created a custom CSS file in the assets folder where I added lines to override certain styles (such as changing th ...

Arranging two stretchable div elements side by side

I'm currently working on a web page layout where I want two divs to be flexible and adjust their size as the browser window is resized. However, I've encountered an issue where instead of shrinking, the line breaks between the two divs when the w ...

Preserving Scroll Location Through Back Button Usage and Ajax Manipulation of the Document Object Model

Currently, I am incorporating a feature where results are loaded in using ajax with an infinite scroll. However, there is an issue when a user clicks on an item in the list and navigates away from the page - upon returning by clicking the back button, they ...

Issues with Angular application navigation in live environment

While my website functions perfectly on the development server, I encounter a strange error when I publish it to production on GitHub pages. Visiting the URL (yanshuf0.github.io/portfolio) displays the page without any issues. However, if I try to access y ...

Ways to remove specific characters from the escape() function in express-validators

When using the check method from express-validator to validate user input, I'm curious if there's a way to exclude certain characters from the test. For example, currently I have: check("profile.about").trim().escape() This code snippet convert ...

The array filtering functionality is not functioning as intended

Struggling with correctly filtering data in JavaScript. Here's an example where var1 = 20, var2 = 10, var3 = 30, var4 = 40. This is the code snippet: var variables = ['var1', 'var2', 'var3', 'var4'], values = [ ...

Exploring JSON data with ReactJS

I am experiencing issues with populating a table with data imported from a JSON file. The error message I'm receiving is: Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {list}). If you intended to render ...

The ng-view in index.html is not being loaded by AngularJS

I've been working on setting up a single-page application using AngularJS. In my setup, I'm using Node with Express and have an Apache server functioning as middleware. The issue I'm facing is that while my index.html page loads without any ...

MERN stack does not have a defined onClick function

I am developing a website for college registration, and I encountered an issue while trying to create a feature that allows students to select a major and view all the associated courses. I made a list of majors with buttons next to them, but whenever I at ...

AngularJS is not responding to a 400 bad request

Despite my efforts to find solutions on Google and Stack Overflow for similar or identical issues, as a newcomer, none of them have provided me with any insight on how to resolve the issues in my code. Here is the script I am working with: $http.post(&ap ...

Generating alternate list items

I'm attempting to design a list style that resembles the one depicted in the image linked below: https://i.stack.imgur.com/U7vMw.jpg My issue is that when I try to add borders, they end up applying to the entire structure. .styled-list { list-st ...