Execute a task prior to invoking a different task

I'm currently working on an image slider that has some interactive features. Here's how it functions:

  1. When a user clicks on an image, it slides and comes to the front.
  2. On the next click, the image is flipped and enlarged.
  3. Then, on another click, the image returns to its original size and position.

If I select a new image while one is already enlarged, I want to create a function that will bring back the first image to its original state before enlarging the new one.

How can this be achieved?

var status = 1;
function flipIt(obj) {

    console.log("value before Function status " + status);

    if (status == 1) {
        alert("I am From JS IF part");
        $(obj).animate({ "left": "-=30px", "opacity": "0.65" }, "slow");
        $(obj).animate({ "height": "400px", "width": "350px" }, 30);

        // Code for flipping the image
        // Additional CSS changes
        status = 0;
        console.log("after if value set status " + status);
    } else {
        alert("I am From JS Else part");
        $(obj).animate({ "left": "+=30px", "opacity": "0.99" }, "slow");
        $(obj).animate({ "height": "354px", "width": "295px" }, 30);

        // Code for bringing image back to original state
        // Additional CSS changes
        status = 1;
        Removecss();

        console.log("ater else value set status " + status);
    }
}

Answer №1

If I follow correctly, it seems like you have a scenario where there is a list of items, and when a user selects one item, a specific action occurs (such as flipping and enlarging an image). However, when the user selects another item from the list, you want the effect on the first item to be reset.

One approach to tackle this issue is by assigning a CSS class to the selected item, let's call it .flipped-and-enlarged. Before applying any transformation to an item in the list, make sure to reverse the effect on any item that already has this class:

function flipAndEnlarge(obj) {
    $('.flipped-and-enlarge').reverseFlipAndEnlarge();

    // carry out the remaining actions
}

This strategy ensures that only one image will be flipped and enlarged at a time if implemented correctly.


It's worth mentioning that using .reverseFlipAndEnlarge() as shown above involves creating it as a jQuery plugin. While the process is straightforward (as indicated here) and highly recommended, if you prefer not to go down that route, you could potentially utilize something like

reverseFlipAndEnlarge($('.flipped-and-enlarged'))
as an alternative solution.

Answer №2

One way to improve your code is by defining a variable that stores the name, class, or id of the current image being viewed/enlarged. You can then call this variable before clicking on the second image like so:

 var currentImage = $(this).attr('class');

In your "if" statement, consider adding another condition to check if the previous image variable is not empty:

 if(yourCondition){
    if(currentImage != ''){
        //resetImageSize();
     }
   //resizeImageAndApplyAnimations..
 }

I hope these suggestions are helpful for you. Keep coding! :) Best regards.

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

The output of jQuery('body').text() varies depending on the browser being used

Here is the setup of my HTML code: <html> <head> <title>Test</title> <script type="text/javascript" src="jQuery.js"></script> <script type="text/javascript"> function initialize() { var ...

"Is it possible to draw on top of a canvas element that's already been

I'm currently working with an OpenLayers map that includes WMS layers with time steps. My goal is to create a loop that updates the time for each step and then saves the image once it's rendered. I've been referencing the example code from t ...

Surrounding the text with background color

My H1 text is in a div that spans multiple lines due to the fixed width of the div. I am looking to set the background color to only appear behind the actual text of the H1, without extending into empty space at the end of each line. In addition, I also n ...

Manipulate component properties using CSS hover in React with Material-UI

I am attempting to modify the noWrap property of a Typography element when hovering over it. I have defined a custom CSS class for the parent element and the hover functionality is working correctly. However, I am unsure how to adjust the noWrap property u ...

Incorporating a dynamic fill effect into an SVG pie chart

I am looking to animate a pie chart with a variable value that is unknown upon loading. Assuming I fetch the value promptly and convert it into a rounded percentage : var percentage = Math.round(sum * 100 / total); Next, I place this value here : <di ...

Gather information from "div" tag with the class attribute using Python

I am looking to extract specific financial data (referred to as the Key data) that is housed within <div> </div> tags. I then aim to consolidate this extracted information into an excel sheet which already contains additional harvested data. Th ...

Resizing a floated div causes the image to break out

My webpage has a container div with two floated left divs inside, positioned side by side. The right div contains a YouTube video and an image. However, when I resize the page, the video and picture flow out of the containing floated div instead of dropp ...

Issue with Bootstrap carousel: image protrudes past boundaries of parent container

Struggling with setting up a bootstrap carousel on my page. I want the image to extend beyond the parent div, positioned at the bottom rather than the top. How can I achieve this without disrupting the default carousel behavior? Here's a sketch of how ...

Styling Input elements with a unified border in Bootstrap

[Issue Resolved] I have been working on setting a single border between multiple inputs inside a form-group in Bootstrap. Currently, the border is only visible when the input is not focused and it is the last one. However, my expectation is for the bo ...

Passing data in JSON format to PHP

I am having trouble sending a JSON to a PHP page using jQuery. The code I have doesn't seem to work as expected: json_data = {}; json_data.my_list = new Array (); $('#table_selected tr').each (function (i) { json_data.my_list.push ({id ...

In JavaScript, a prompt is used to request the user to input a CSS property. If the input is incorrect,

Implement a while loop that continuously prompts the user to enter a color. If the color entered matches a CSS property such as blue, red, or #000000: The background will change accordingly, but if the user enters an incorrect color, a message will be dis ...

Have you heard of the JQuery Accordion plugin?

I am struggling with setting the height of the content box in my accordion, which has 3 sections. I want the content to fit perfectly without any need for scrolling. Despite trying various solutions, I have not been able to achieve the desired outcome. To ...

Getting the first nested object within an object in Angular 8: A comprehensive guide

Looking to extract the first object from a JSON data set? In this case, we want to retrieve {"test": {"id":1, "name":"cat"}} from the following object: { "3": {"test": {"id":1, "name":"cat"}}, "4": {"test": {"id":2, "name":"dog"}}}. Keep in mind that the ...

React component rendering twice due to width awareness

In a React component that I've developed, I have utilized ResizeObserver to track its own width. Within this component, two divs are rendered with each having a "flex: 1" property to ensure equal width distribution. Under certain conditions, such as w ...

Material-UI Grid in Full Width Mode is malfunctioning

I've been delving into the Material-UI@next grid layout system to grasp its intricacies. What I'm aiming for is to have two papers that stretch across the entire width of the screen and collapse into one paper when the screen size shrinks. The d ...

conceal elements created with JQuery within an AJAX function

Is it possible to use jQuery and the $.ajax() method to submit a form, displaying only the result while hiding other elements on the page? I am looking to add a conditional in the Ajax method that will show the result if successful, hiding certain elements ...

Challenges with utilizing multiple backgrounds in CSS

<!DOCTYPE html> <html lang="en"> <head> <meta name="description" content=""> <meta name="author" content=""> <title>Main Website</title> <link href="css/main.css" rel="stylesheet"> </head> ...

Is it required to double click checkboxes to uncheck them?

My checkboxes require 2 clicks to be unchecked, even though one click is enough to check them. This issue occurs in all 7 checkboxes and there is no onchange() function or similar in TS. import { Component, OnInit, Inject } from '@angular/core&apos ...

Updating Github pages requires clearing the cache first

As I work on my first website using GitHub pages, I've noticed that it can be frustrating to constantly clear the cache or open an incognito window whenever I add something new. I'm thinking about incorporating Jekyll into my workflow so I can t ...

The arrangement of columns and floating images along with the surrounding white spaces

There are 3 columns, each sized at 33% with images of varying heights inside. When viewed on a device the size of an iPad, I want to change the column sizes to be 50%. However, when I do this, the third column appears in the middle bottom of the top two co ...