Once the if condition is implemented, the functionality of the toggle button ceases to operate

Take a look at this demo link: http://jsbin.com/labuxuziraya/1/edit

I encountered an issue where the button stops working after adding an if condition. I suspect there are some minor bugs in the code, but my level of experience is not enough to pinpoint them.

Your help would be greatly appreciated.

Here's the HTML code snippet:

<div class="div1 active">press outside the div to expand again</div>
<span class="btn btn-default">toggle to expand<span>

And here's the CSS snippet:

div {
background: lightgrey;
width: 200px;
height: 400px;
float: left;
padding: 15px;
margin: 15px;
}

.active {
   width: 50px;
 }

Finally, the JavaScript code:

function Trigger() {
 $('.div1').toggleClass('active');
 }


 $('.btn').on('click',function(){
   Trigger();
});


 $(document).click(function(event) { 
 if(!$(event.target).closest('.div1').length)
 {
     if( $('.div1').hasClass('active') )
    {Trigger();}        
  });

Answer №1

It appears that you can simplify your code based on Lal / LinkinTED's feedback. You may consider removing the

if( $('.div1').hasClass('active') )
condition as it is already handled in the toggleClass function. A more straightforward solution would be:

$(document).click(function(event) { 
    if (!$(event.target).closest('.div1').length) {
        $('.div1').toggleClass('active');
    }        
});

If you decide to keep your original condition, you might be duplicating efforts by reinventing the wheel (the toggle function) and needing to create activate / deactivate functions to use within your if / else statement:

function activate() {
     $('.div1').addClass("active");
}

function deactivate() {
     $('.div1').removeClass("active");
}

$(document).click(function(event) {
    if(!$(event.target).closest('.div1').length) {
        if ( $('.div1').hasClass('active') ) {
            deactivate();
        }
        else {
            activate();
        }
    }
}

Answer №2


function ToggleClass() {
   $('.element1').toggleClass('activate');
 }


 $('.button').on('click',function(){
     ToggleClass();
 });

 $(document).click(function(event) {
 var clickedElement = event.target;

 //if they click any element other than .element1, and .element1 is not activated then activate it.

 if(!$(clickedElement).hasClass('.element1') &&  !$('.element1').hasClass('activate'))
      ToggleClass();        

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

Utilizing ease-in effect on show more button clicks in CSS

When I click "show more," I want to have a smooth ease-in/out animation for 3 seconds. However, I am facing difficulties achieving this because I am using overflow: hidden and -webkit-line-clamp: 2; Are there any other methods to accomplish this? https: ...

"Terminate the current window that is open within the handler for the XMLHttpRequest

Currently, my approach involves using Javascript and Ajax to retrieve data and display it in a new window. I am encountering an issue where I am trying to close the window in the OpenFileWindow() function before opening a new one, but I am facing a permiss ...

Incorporate 'Additional features' into the Navbar when adjusting window size

When the window is resized, I want to display a collapsed 'More options' button that will collapse all hidden <li> elements. Here is an example: <li id="menu_more_container" class="dropdown" style="display: none; ...

Is there a method to initiate a 'simple' action when dispatching an action in ngrx?

Here's the scenario I'm facing: When any of the actions listed below are dispatched, I need to update the saving property in the reducer to true. However, currently, I am not handling these actions in the reducer; instead, I handle them in my ef ...

I was confused about the distinction between the https.get() and https.request() functions in the Node.js npm package for https

// # Exciting Nodejs Programs! const https = require('https'); https.get('https://www.google.com/', (res) => { console.log('statusCode:', res.statusCode); console.log('headers:', res.headers); res.on ...

The absence of jQuery is causing an issue in the webpack +Angular 4+ Asp Core template

I am currently working on a project that was created using the VS 2017 Angular 4 + Asp Core template. I have decided to incorporate a jQuery plugin into my project, which requires me to import jQuery. In my .ts file, I have included the following line of c ...

Utilizing jQuery with variable assignment: A beginner's guide

Struggling to utilize a variable in jQuery? In the script snippet below, I set a variable "divname" with a value, but when using jQuery for fading out, it doesn't work as expected. What I really want is for the description to fade in when hovering ove ...

Dynamic Field Validation in Angular 6: Ensuring Data Integrity for Dynamic Input Fields

After successfully implementing validation for one field in my reactive form, I encountered an issue with validating dynamically added input fields. My goal is to make both input fields required for every row. The challenge seems to be accessing the forma ...

Sharing numerous pictures in a single line using comma-separated pathways

I am trying to enhance my code by allowing users to select multiple images simultaneously and on submit click, I want to store the file paths in MySQL database as comma-separated values in a single row. Below is the code snippet that I have implemented: C ...

"Ionic application encountering issue with retrieving data from email inbox, resulting in undefined

I encountered an issue with creating a user account using Ionic Framework and Firebase. Oddly, the email box returns 'undefined' while the password box functions correctly despite being coded in a similar manner. Below is my HTML snippet: <io ...

TypeScript Yup schema validation combined with the power of Type Inference

I currently have a unique data structure as shown below: type MyDataType = | { type: "pro"; content: { signedAt: string; expiresOn: string }; } | { type: "default" | "regular"; content: { signed ...

Display images in a list with a gradual fade effect as they load in Vue.js

In my Vue project, I am looking to display images one at a time with a fading effect. I have added a transition group with a fade in effect and a function that adds each image with a small delay. However, I am facing an issue where all the images show up ...

Is it possible for a Vue.js build to encounter errors due to unregistered components?

Exploring a component template... <template> <Unknown></Unknown> </template> In the context of this template, Unknown could be either a globally registered component or not. Upon encountering this scenario at runtime, an informa ...

Using the onClick function to set attributes in React JS

I am currently working with 2 functions: addBookmark() and removeBookmark(). There is a variable called IsBookmarked that can be either true or false. In my JSX code related to bookmarks, it looks like this: {props.singleCompany.IsBookmarked ? ( ...

Guide for displaying SQL data in an HTML table

I am currently working on transferring my SQL data to an HTML format. The code I have so far is not functioning as expected. I attempted to include HTML within my PHP code, and now I am considering if it would be better to do it the other way around (emb ...

What could be the reason for the history.length being 2 on the initial page?

Why is it that when I open a new browser window and load a page in it, the history.length property is always 2 in both Chrome and Firefox? You can test this phenomenon yourself by visiting the following link: http://jsbin.com/amiyaw ...

The Angular directive is failing to refresh the data on the Google Map

I created a directive called "myMap" to incorporate a Google map into my application. However, I am facing an issue when attempting to update the longitude and latitude values for a different location using a controller function. The directive does not ref ...

Mars Eclipse, AngularJS and the power of NodeJS

Could you please assist me in understanding the workings of node.js and angular.js within Eclipse? I am using Eclipse Mars and I would like to run my Angularjs project on a local server (localhost:8080) but I am unsure of how to accomplish this. I have a ...

Why does my <p> element in Bootstrap continue to elongate and push everything below it down when I minimize the window?

I've got a standard bootstrap layout set up. <div classs="row-fluid"> <div class="span12" style="background:black; padding:25px 0px;">content content</div> </div> <div class="span4 offset2"> <p>blah blah bl ...

I have implemented the appropriate code to showcase a background color, yet it doesn't seem to be appearing on the screen. Additionally, I am utilizing Sass in this project

Could someone help me understand why the background color is not showing on my website? This is the CSS I am using html { font-size: 100%; -webkit-box-sizing: border-box; box-sizing: border-box; } *, *::before, *::after { -webkit-box-sizi ...