When using a jquery if statement and .each loop, the if statement may not always run

I'm facing an issue where an unexpected if statement is being triggered. I am working on creating a transition between two images on click. Once the transition is complete, I add a class to the body to show and hide some content. My goal is to reverse the transition by adding a class to the body and moving the image back into place.

The problem arises when running the code below (offset definitions omitted). The initial transition works as intended - executing the code in the first if statement and adding the 'expand' class to the body. However, upon clicking again to revert the transition, the 'expand' class is removed from the body, the image transitions but then 'expand' is added back to the body (the first if statement runs after the transitions).

Is there a way to prevent the initial if statement from triggering and adding 'expand' back to the body on the second click/transition?

Thank you for your assistance!

$('.picture-item').click(function(){

if (!$('body').hasClass('expand')) {
  var length = $('.match').length;

  $('.match').each(function(i) {
    // get the data value for the equivalent pictures 
    var pictureMatch = $(this).data('image');

    $(this).find('.picture-item-background').css({ '-webkit-transform':'translate('+offsetLeft+'px, '+offsetTop+'px) scale('+offsetScale+')'});
    if(length == i+1){
      $('.match').find('.picture-item-background').on('transitionend webkitTransitionEnd oTransitionEnd', function () {
          $('body').addClass('expand');
      });
    } 
    i++;

  });  
}

if ($('body').hasClass('expand')) {        
  $('body').removeClass('expand');
  $('#minimized').on('transitionend webkitTransitionEnd oTransitionEnd', function () {
    $('.picture-item-background').css({'-webkit-transform':'translate(0px,0px) scale(1)'});
  });
}

return false;
event.stopPropagation();  

});

Answer №1

Upon initial inspection, it seems like all you need is to include an else statement in your code:

$('.picture-item').click(function(){

  if (!$('body').hasClass('expand')) {
    // your code 
  } else {   // remove if ($('body').hasClass('expand')) {        
   // continue with the rest of your code
  }
  return false;
  event.stopPropagation();  
});

By making this adjustment, only one section of the code will execute with each click. Currently, if the class is not present, the first section of code runs and adds the class. The subsequent section of code will always run because the class has already been added.

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

What is the method for overlaying an image and having it expand to fit the parent container using flexbox?

I'm working on styling an HTML element where I want the txt-box div to be centered within its container, overlaying an image while expanding to fill the container. The goal is for it to have a margin of equal width on all sides, creating a border-like ...

The innerHTML property of the iframe element returns null

Yesterday, the code was functioning properly as iframe[0].contentWindow.document.body.innerHTML displayed "success". However, today, both iframe[0].contentWindow.document.body and iframe[0].contentDocument.body are empty. The innerHTML cannot be found. ht ...

A contact form overlaying a muted Google Maps view in an HTML website

Currently, I am in the process of developing a website that features a contact form. It would be great if I could incorporate Google Maps as a background, but with a greyed-out effect instead of a plain white page. After trying out a few solutions, I ende ...

Error message "Encountered an unknown type 'ForOfStatement' when attempting to execute an npm library"

Currently, I am in the process of integrating the PhotoEditor SDK library into my Ruby on Rails project. To achieve this, I have been meticulously following the installation guidelines provided in the official documentation. However, during the setup proce ...

Caution: Potential issue observed when utilizing Enzyme within beforeEach in a Typescript environment

Presently, here is my code snippet: const MyComponent = () => ( <Provider store={storeRedux}> <BrowserRouter> <Context.Provider value={...}}> <Mode { ...props } /> </Context.Provider> </Br ...

The NextRouter failed to mount

Currently, I am in the process of incorporating a search functionality into my property rental application. I have successfully added the Nextjs Router to handle the routing. However, when attempting to access localhost:3000/search, an error is encountered ...

Mastering the art of looping through an array efficiently in jQuery using AJAX without unnecessary repetition

I have a jQuery function that extracts values from the wp_localize_script declaration. <script type='text/javascript'> /* <![CDATA[ */ var assjs = {"action":"get_ass_counts","path":"http:\/\/localhost\/wordpress-dev\ ...

Incorporate socket.io into multiple modules by requiring the same instance throughout

I am feeling a bit lost when it comes to handling modules in Node.js. Here's my situation: I have created a server in one large file, utilizing Socket.io for real-time communication. Now, as my index.js has grown quite big, I want to break down the ...

Placing a box in the center of its parent container using CSS positioning

Check out this code snippet : HTML <div class="app-cont"> <div class="app-head"> Additional Comments : </div> <div class="app-main"> balallalalalallalalalala <br/> jaslnflkasnlsnlk ...

Modifying my code: utilizing toggle() and toggleClass() at the moment

Confusion in Code Communication The following IDs lack proper communication: #html-button #css-button #js-button #result-button To address this, I introduced a new class called .selected. The code functions well with the current setup. However, removin ...

Guide on obtaining the highest Z-index value from multiple elements using JQuery

Currently tackling a bug that's stumping my senior dev. Here's the issue at hand: In my dashboard, users can drag and drop multiple elements, customizing their placement. However, every time a new element is added, its z-index defaults to ' ...

incorrect <div> <img src="<?php under construction?"

When I try to display images using the construction <div> <img src="<?php..., the images appear as intended. However, there are extra strings leftover from my code after each image. An excerpt of the problematic code: First, I retrieve ...

Set a live Vuejs data binding to style properties

Check out this JSFiddle I have: https://jsfiddle.net/6cu295sn/1/ new Vue({ el: '#cct', lang: { myText: "my text is", } }); .myCSS::after{ content: {{lang.myText}}; //this does not output anything } I'm looking for ...

The elements being parsed are appearing as undefined

Currently, I am attempting to analyze this JSON structure: { "customers": [ { "name":"joe" , "cars":[ {"name":"honda","visits":[ {"date":"01/30/14","Id":"201"}, {"date":"01/30/14","Id":"201"}, {"date":"02/12/14","Id":"109"} ...

Using Angular JS to compare and display the changed value in a textbox from its previous value

This is the code I am working with <body> <div> <table ng-app='myApp' ng-controller="MainCtrl"> <thead></thead> <tbody ng-repeat="prdElement in palletElement track by $index&quo ...

Creating data structures for reactive forms in Angular

I am currently working on a HTTP post service that requires a date and time in the format: YYYY-MM-DDTHH:MM:SSZ One of the forms I am working with has a formGroup structured like this: this.formBuilder.group({ name: [''], startDate: [null], ...

Manipulating and filtering an array of objects in JavaScript/jQuery

Looking to simplify my array manipulation in Javascript, I need to subset based on key-value matches. I have an array called js_obj, and my goal is to modify objects where a certain condition is met. Consider the structure of my array: js_obj = [{ wo ...

Initial Troubles with Bootstrap Tabs

Currently, I am working on setting up two basic tabs and panels. When the page loads, the content (Page 1) in the panel does not display, although clicking on the second tab shows the correct content (Page 2). Interestingly, when I go back to the first tab ...

Unveil/Conceal Div Overlay

Something seems to be off with my current script. When I click on a link in the table, the div overlay is created successfully. However, when I close the div and click on another link, the overlay pops up again and the close button no longer works. I susp ...

Detecting Memory Leaks in a Node.js/Express.js Application

I've been dealing with memory problems in my Express.js web app lately. It keeps crashing with the following error: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory Initially, when I launch the service, the memory u ...