Disable class upon clicking outside the element

Whenever I click outside and the default text reloads, I want the previously clicked class to be removed. For example, if I select "Fair Trade" and it changes color to red, that selection should fade away when I click outside and the default text reappears, similar to how it fades away when I click on another title.

var $imgs = $(".section-link");
...

// JavaScript code for handling clicks and animations

.section-link {
  width: 100px;
  
  -webkit-transition: all .5s ease-in-out;
  -moz-transition: all .5s ease-in-out;
  -ms-transition: all .5s ease-in-out;
  -o-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
}
.section-link.clicked{
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section-link small-solid-circle-p4 fair-d">
  <h2>
    <nobr>FAIR-TRADE</nobr>
  </h2>
</div>
<div class="section-link small-solid-circle-p4 toxic-d">
  <h2>TOXICFREE</h2>
</div>
<div class="section-link small-solid-circle-p4 quality-d">
  <h2>QUALITY</h2>
</div>
<div class="section-link small-solid-circle-p4 organic-d">
  <h2>ORGANIC</h2>
</div>
<div class="section-link small-solid-circle-p4 vegan-d">
  <h2>VEGAN</h2>
</div>
<div class="section-display active info-p4">
  <h2 class="title1">Lorem ipsum</h2>
  <h2 class="text1">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.<br>
  <br> Tap on the symbols if you want to know more.</h2>
</div>

Answer №1

Include this line to the code: $($imgs).removeClass('clicked')

var $imgs = $(".section-link");

var data = [{
        title: "Fair Trade",
        text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
    },
    {
        title: "Toxicfree",
        text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
    },
    {
        title: "Quality",
        text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
    },
    {
        title: "Organic",
        text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
    },
    {
        title: "Vegan",
        text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
    },
];

// Get reference to the output area
var $outputDiv = $(".section-display");
var defaulttext = $outputDiv.find(".text1").html()
var defaultTitle = $outputDiv.find(".title1").html();

$imgs.on("click", function() {

    $This = $(this);

    $imgs.removeClass("clicked");
    $This.addClass("clicked");

    $(".title1", $outputDiv).animate({
        opacity: 0
    }, function() {
        $(".title1", $outputDiv).html(data[$This.index() - 1].title)
            .animate({
                opacity: 1
            });
    });
    $(".text1", $outputDiv).animate({
        opacity: 0
    }, function() {
        $(".text1", $outputDiv).html(data[$This.index() - 1].text)
            .animate({
                opacity: 1
            });
    })
});

$(document).on("click", function(e) {
    if ($(e.target).closest('.section-display').length != 1 && $(e.target).closest(".section-link").length != 1) {
        $(".title1", $outputDiv).animate({
            opacity: 0
        }, function() {
            $(".title1", $outputDiv).html(defaultTitle)
                .animate({
                    opacity: 1
                });
        });
        $(".text1", $outputDiv).animate({
            opacity: 0
        }, function() {
            $(".text1", $outputDiv).html(defaulttext)
                .animate({
                    opacity: 1
                });
            $($imgs).removeClass('clicked')
        })
    }
})
.section-link {
  width: 100px;

  -webkit-transition: all .5s ease-in-out;
  -moz-transition: all .5s ease-in-out;
  -ms-transition: all .5s ease-in-out;
  -o-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
}
.section-link.clicked{
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section-link small-solid-circle-p4 fair-d">
  <h2>
    <nobr>FAIR-TRADE</nobr>
  </h2>
</div>
<div class="section-link small-solid-circle-p4 toxic-d">
  <h2>TOXICFREE</h2>
</div>
<div class="section-link small-solid-circle-p4 quality-d">
  <h2>QUALITY</h2>
</div>
<div class="section-link small-solid-circle-p4 organic-d">
  <h2>ORGANIC</h2>
</div>
<div class="section-link small-solid-circle-p4 vegan-d">
  <h2>VEGAN</h2>
</div>
<div class="section-display active info-p4">
  <h2 class="title1">Lorem ipsum</h2>
  <h2 class="text1">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.<br>
  <br> Tap on the symbols if you want to know more.</h2>
</div>

Answer №2

The non-breaking tag I used for fair-trade caused a disruption in my logic, so I decided to remove it;

Other than that adjustment, this modification should align with your specifications.

var $imgs = $(".section-link");


var data = [{
    title: "Fair Trade",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Toxicfree",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Quality",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Organic",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Vegan",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
];

// Get reference to the output area
var $outputDiv = $(".section-display");
var defaulttext = $outputDiv.find(".text1").html()
var defaultTitle = $outputDiv.find(".title1").html();

$(window).click(function(e) {
if(!e.target.parentNode.classList.contains('clicked')) $(".section-link.clicked").removeClass("clicked")
});


$imgs.on("click", function() {


  $This = $(this) ;
  
  $imgs.removeClass("clicked") ;
  $This.addClass("clicked");
    
  $(".title1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".title1", $outputDiv).html(data[$This.index() - 1].title)
      .animate({
        opacity: 1
      });
  });
  $(".text1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".text1", $outputDiv).html(data[$This.index() - 1].text)
      .animate({
        opacity: 1
      });
  })
});

$(document).on("click", function(e) {
  if ($(e.target).closest('.section-display').length != 1 && $(e.target).closest(".section-link").length != 1) {
    $(".title1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".title1", $outputDiv).html(defaultTitle)
        .animate({
          opacity: 1
        });
    });
    $(".text1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".text1", $outputDiv).html(defaulttext)
        .animate({
          opacity: 1
        });
    })
  }
})
.section-link {
  width: 100px;
  
  -webkit-transition: all .5s ease-in-out;
  -moz-transition: all .5s ease-in-out;
  -ms-transition: all .5s ease-in-out;
  -o-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
}
.section-link.clicked{
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section-link small-solid-circle-p4 fair-d">
  <h2>
    FAIR-TRADE
  </h2>
</div>
<div class="section-link small-solid-circle-p4 toxic-d">
  <h2>TOXICFREE</h2>
</div>
<div class="section-link small-solid-circle-p4 quality-d">
  <h2>QUALITY</h2>
</div>
<div class="section-link small-solid-circle-p4 organic-d">
  <h2>ORGANIC</h2>
</div>
<div class="section-link small-solid-circle-p4 vegan-d">
  <h2>VEGAN</h2>
</div>
<div class="section-display active info-p4">
  <h2 class="title1">Lorem ipsum</h2>
  <h2 class="text1">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.<br>
  <br> Tap on the symbols if you want to know more.</h2>
</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

Converting a PHP timestamp to a jQuery-compatible format

Can someone help me find the equivalent function in jQuery that will give me a time format similar to this: date( 'Y-m-d\TH:i:sP'); //the output is like this. 2013-10-30T18:10:28+01:00 I am looking for this specific format in jQuery to use ...

VBA: A guide to interacting with elements inside an iframe

I've been struggling to click on an element within an HTML iframe for weeks now. I've tried clicking on a div ID and a span title, but nothing seems to work. I believe it's due to incorrect syntax. Can someone please advise me on the correc ...

How can you make a form group expand within a container in Bootstrap 4?

After experimenting with the paddings, I still couldn't resolve the issue at hand. The goal is to extend these fields all the way to the right side. Check out the Fiddle for comparison between the current appearance and the desired look. The stylin ...

Steps to Verify if Cookie is Turned Off in a Next.js Application

I have encountered an issue with my Next.js App. It seems to be functioning properly until I disable cookies in the browser. Is there a way for me to determine if cookies are disabled in the browser and display a corresponding message? I attempted to check ...

What is the method to extract information from the provided URL?

Hello, I am looking to retrieve system requirements data from . How can I achieve this using JS or react? ...

At what point are routed components initialized?

Here is a route setup I am working with: path: ':id', component: ViewBookPageComponent }, After adding this route, an error keeps popping up: Error: Cannot read property 'id' of null I haven't included a null check in the compo ...

Warning: Potential Infinite Loop when using Vue JS Category Filter

I developed a program that filters events based on their program and type. The program is working correctly, however, an error message stating "You may have an infinite update loop in a component render function" keeps popping up. I suspect that the issue ...

Seeking recommendations for a reliable source on learning MVC3 and Jquery with parameters

I have been attempting to use jQuery.post to send back the Model data. Despite searching on Google, I am unable to find a detailed example of using $.post with data that includes passing back the Model. ...

Generate a customizable URL for my search bar

I have developed a single HTML page with full AJAX functionality, displaying all content including form submits, main page, form results, and more through various DOM manipulations. The issue I am currently encountering is related to a search box where use ...

What would be the best way to improve the efficiency of this particular function

I have two functions that are responsible for adding and removing data from an endpoint. Currently, I have one function for adding data and another for removing data. const addMultipleAuthorities = async () => { const postMultipleAuthoritiesData = ...

Executing JavaScript code with Node.js while utilizing Selenium

Seeking guidance as a beginner in Javascript, I apologize if my question is too basic. I am attempting to execute a Selenium test written in Javascript. Starting with a simple task of loading Google using chromedriver, I encountered an issue while running ...

concealing the upper header while scrolling and shifting the primary header upwards

Is there a way to use CSS to move the main header navigation, including the logo and links, on my website up when scrolling down in order to hide the top black bar header that contains contact information? The website in question is atm.truenorthmediasol ...

What is the best way to swap out a div element with a text area when I press a button, all

I recently used a Fiddle found at http://jsfiddle.net/GeJkU/ function divClicked() { var divHtml = $(this).html(); var editableText = $("<textarea />"); editableText.val(divHtml); $(this).replaceWith(editableText) ...

Issues occur when attempting to save comments from the frontend in a Django environment

Hey there, I'm having some trouble with comments on my website. When using Class Based Views (CBV), the form is not saving the comments. Below is the code snippet from my models.py: class Product(models.Model): title = models.CharField(ma ...

Issue with Datatables footer: Uncaught error - Unable to assign property 'nTf' due to it being undefined

I have encountered a problem with datatables while handling a large number of records (45,000 +). To deal with this, I am implementing datatables using "Server Side" coding. The issue at hand is that an error message keeps popping up in the code snippet b ...

The position of the <input> element shifts once the user provides input

I'm currently developing a web-based self-quizzing application, but I've encountered an issue with my input form. Each input field is placed in its own cell within a table for organization purposes. To maintain an aesthetically pleasing structure ...

Removing the gaps within table cell contents

Is there a way to eliminate the border space between cells in a table? Despite using cellspacing, I still see a thin white border. Any suggestions on how to fix this? <body> <center><table style="border-collapse: collapse; width:400px; bo ...

Checking and merging arrays in Javascript

I have a unique challenge involving two arrays of objects that I need to merge while excluding any duplicates. Specifically, if an object with the key apple: 222 already exists in the first array, it should be excluded from the second array. Please see be ...

How to convert a JSON response into a select box using VueJS?

I have a VueJS component where I need to populate a html select box with data from a JSON response. This is my VueJS method: getTaskList() { axios.get('/api/v1/tasklist').then(response => { this.taskList = this.data.taskList; ...

Determine when an item is checked in a React array

In the code snippet below, I have a method that toggles the checked state of an element when clicked. const [elements, setElements] = useState([]); const handleElementClick = (index) => { setElements(prevState => { return prevState.map(( ...