skip to Main Content

I using same onclick function on two span, When clicking on text 1 span it is adding active class and when clicking again removing the class. It is working fine on both span’s.
I just want if when clicked text 1 span so the active class is added to text 1 span and when i click on text 2 span add active class to this span but remove it from text 1 span.
Available on codepen https://codepen.io/hnpiocyj-the-encoder/pen/VwRZBrW

<span class="selected" onclick="select(this);">text 1</span>
<span class="selected" onclick="select(this);">text 2</span>
function select(i){
    e = window.event
    $(i).toggleClass("active");
    e.stopPropagation();
}

I want if text 1 span has active class and when i click on text 2 span add active class but also i want to remove the active class from text 1 span.

6

Answers


  1. To do what you require you simply need to remove the class from all other .selected elements, except the one which you clicked on.

    Also note that there’s a couple of other changes your should make to improve the quality of your code. Firstly, don’t use inline onclick attributes. They’re bad practice and have been superceded by unobtrusive event handlers which can be bound in the JS itself.

    Seconly, don’t use the global window.event object as it’s not available in all browsers. If you use unobtrusive handlers, then your handler function will be provided the Event as an argument which you can use to identify the element that fired the event.

    With those changes made, your code would look something like this:

    const spans = document.querySelectorAll('.selected');
    
    const toggleActiveClass = e => {
      e.stopPropagation();
      
      // toggle the class on the current element
      e.target.classList.toggle('active');
      
      // remove the class from all other elements
      spans.forEach(span => {
        if (span !== e.target) {
          span.classList.remove('active');
        }
      });
    }
    
    spans.forEach(span => span.addEventListener('click', toggleActiveClass));
    .active {
      background-color: #C00;
      color: #FFF;
    }
    <span class="selected">text 1</span>
    <span class="selected">text 2</span>
    Login or Signup to reply.
  2. You just need to get all the active spans in your function and remove the active class from them. After removing, you can make use of your this object, passed in the function argument, to add a new active class.

    See the demo below:

    function select(currObj) {
      const allActiveSpans = document.querySelectorAll('span.active');
      allActiveSpans.forEach(span => {
        if(span !== currObj){
          span.classList.remove('active');
        }
      });
      currObj.classList.toggle('active');
    }
    .active {
      border: 1px solid;
    }
    <span onclick="select(this);">text 1</span>
    <span onclick="select(this);">text 2</span>
    Login or Signup to reply.
  3. If you are using jQuery, you can use it’s function is() to check if the target element is equal to another element:

    function select(i){
       //get the clicked element as a jQuery object
       const $clicked = $(i);
       //iterate each span with the className 'selectable'
       //added className `selectable` to the spans that you want to
       //use so you don't have to select every span on the page
       $('span.selectable').each(function(i, el) {
           //use jQuery .is to see if the element is the one that was clicked
           //if not remove the class active else toggle the class
           if(!$(el).is($clicked)){
              $(el).removeClass('active');
           } else {
              $(el).toggleClass('active');
           }
       });
    }
    .active {
      background-color: #C00;
      color: #FFF;
    }
    <script
      src="https://code.jquery.com/jquery-3.7.1.min.js"
      integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
      crossorigin="anonymous"></script>
    <span class="selectable" onclick="select(this);">text 1</span>
    <span class="selectable" onclick="select(this);">text 2</span>
    Login or Signup to reply.
  4. To achieve the behaviour you’re looking for, where clicking on one span adds the ‘active’ class to it and removes the ‘active’ class from the other, you’ll need to modify your select function. Currently, your function toggles the ‘active’ class for the clicked element but doesn’t affect the other element. Here’s an updated version of the function that should work for your requirements:

    function select(i) {
      // Prevents the event from affecting parent elements
      e = window.event
      e.stopPropagation();
    
      // Adds 'active' class to the clicked element
      $(i).addClass("active");
    
      // Removes 'active' class from all other '.selected' elements
      $('.selected').not(i).removeClass('active');
    }
    
    Login or Signup to reply.
  5. Also…

    const spans = document.querySelectorAll('.selected');
    
    function select(element)
      {
      if ( element.classList.toggle('active') ) // this method return a Boolean value
        {
        spans.forEach( sp =>
          { 
          if (sp !== element)
            sp.classList.remove('active');
          })
        }
      }
    .active {
      background-color : #C00;
      color            : #FFF;
      }
    <span class="selected" onclick="select(this);">text 1</span>
    <span class="selected" onclick="select(this);">text 2</span>
    Login or Signup to reply.
  6. You can simply use the below jQuery code to achieve this.

    //This is document ready function
    $(function() { 
    
      // add a click handler for the spans that are direct children of .holder
      $(document).on("click", ".holder>span", function(){
        
        // here $(this) is the current clicked span element
        const that = $(this);
        
        // remove active class of clicked span's siblings
        that.siblings().removeClass('active');
        
        // add an active class for current element
        that.addClass('active');
      });
    });
    .holder span{
      border: 1px solid rgba(225,22,22, 0.1);
      background-color: rgba(22,220,22, 0.3);
      padding: 5px 10px;
      cursor: pointer;
    }
    .holder span.active{
      background-color: rgba(22,222,22, 0.6);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="holder">
      <span>Text 1</span>
      <span>Text 2</span>
      <span>Text 3</span>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search