Execute the function if the element has a specific class; otherwise, execute a different function

Currently, I am working on a page where I need to make an element draggable.

Upon clicking on the element, I add the 'active' class which expands the div along with the image inside it.

Initially, the div is structured as...

<div class="work-showcase">

After clicking, it changes to...

<div class="work-showcase active">

I want to create a condition where if the div has the class 'active', then perform function X, otherwise perform function Y.

$(body).click(function(){

        if($('.work-showcase').hasClass('active')){

            var bleft = 4900 ;
            var bright = $(window).width() - 200;

            $('.active > ul li').draggable({
                 axis: "x", 
                 revert: false,
                 stop: function(event, ui) {
                    if(ui.position.left < -bleft)
                    {   
                    $(this).animate({"left": "0px"}, 600);
                    }
                    if(ui.position.left > bright)
                    {   
                    $(this).animate({"left": "0px"}, 600);
                    }

                }
            });


            } else {


     var sleft = 1846 ;
     var sright = $(window).width() - 200;

            $('.work-showcase > ul li').draggable({
                 axis: "x", 
                 revert: false,
                 stop: function(event, ui) {
                    if(ui.position.left < -sleft)
                    {   
                    $(this).animate({"left": "0px"}, 600);
                    }
                    if(ui.position.left > sright)
                    {   
                    $(this).animate({"left": "0px"}, 600);
                    }

                }
            });

        }

    });

However, I am facing an issue with my If statement not functioning as expected...

Answer №1

Consider using this code snippet instead of your current implementation (please notify me if you encounter any issues)

$('body').click(function () {
    var drag, left, right;

    if ($('.work-showcase').hasClass('active') === true) {
        drag = '.active > ul li';
        left = -4900;
        right = $(window).width() - 200;
    } else {
        drag = '.work-showcase > ul li';
        left = -1846;
        right = $(window).width() - 200;
    }

    $(drag).draggable({
        axis: 'x',
        revert: false,
        stop: function (event, ui) {
            if (ui.position.left < left) {
                $(this).animate({'left': '0px'}, 600);
            } else if (ui.position.left > right) {
                $(this).animate({'left': '0px'}, 600);
            }
        }
    });
});

Answer №2

The following code snippet :

$(body).click(function(){ ... });

should actually be written as :

$('body').click(function(){ ... }

Make sure to include the quotes!

Answer №3

Using jQuery:

if($(this).hasClass("active")){
    //perform this action
} else {
    //perform another action
}

Note: The jQuery hasClass method returns either true or false: jQuery hasClass Documentation

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

My PHP code keeps prompting me with an "invalid password" message even though I am confident that the password is correct

As part of a project at work, I am creating an intentionally flawed application to showcase common security vulnerabilities. This application is designed to demonstrate improper practices and may even entice those looking to exploit it. We have robust logg ...

Is it possible to establish globally applicable values using CSS?

Is it possible to set global attributes within a wordpress site to override all instances of specific CSS styles across multiple locations for themes, 3rd party plugins and more? For instance, if I want to apply 'border-radius: 0px;' to all butt ...

To ensure responsiveness in JavaScript, adjust the width to 100%

Recently, I came across this piece of code: <div style="text-align:center; max-width:500px; width:100%; margin:auto"> <script type="text/javascript" src="transition_example.js"></script></div> Here is the content of transition ...

Guide to creating an endless loop animation within a frame

<div className="sound-wave-container py-8"> <img src={!recording ? Wave : DottedLine} className={!recording ? "sound-wave" : ""} alt="Sound Wave" /> </div> ...

Passing data from parent component to child component in React

For my static website using React or Gatsby, I need to pass a prop or boolean variable from subpages to the main layout component in order to determine whether to display a Hero image. Here is a simplified version of the code for the page: import React f ...

Having issues sorting the ranking table numerically in a Javascript/jQuery/JSON/localStorage game

I have successfully created a leaderboard for my game, but I am struggling to automatically sort the scores from high to low. I believe that placing the objects into an array and then sorting them may be the solution, however, I am unsure of how to do th ...

Angular is using the previous parameter value upon clicking the button

I'm currently working on implementing a button that, when clicked, triggers a function sending a parameter to my server. Here is what I have so far: <table class="table table-hover"> <thead> <tr> <th>Id</th& ...

Display outcomes from various APIs using PHP and JavaScript

As someone new to PHP and JS, I am looking to create a script that can scan an API URL at The script should scan for values of userid from 0 to 100 and only display API results that match values found in a specific array. Results that do not align with th ...

Is there a way to retrieve random data based on either product id or slug within a single component using useQuery? Currently, all components are displaying the same data

Here is the code I wrote: const fetchCartItem = async () => { if (token) {const {data } = await axios.get(API.GET_PRODUCT_DETAILS_BY_PRODUCT_ID.replace("[ProductID]",item?.ProductID),{headers:{Authorization: token,},});setCartLoading(fal ...

What is the simplest method for showcasing an image after it has been created on a node.js web server with the help of express?

After developing a mini web server with node.js and the express 4 framework, I implemented a feature where users can upload image files from the main page. The uploaded images are sent to the server through the multer middleware, processed by a python scri ...

What is the process for integrating a Browserify library module into a project as a standard file?

I have successfully developed a JavaScript library module with browserify --standalone, passing all tests using npm test. Now, I am working on creating a demo application that will utilize this library module in a browser setting. When I run npm update, th ...

Only send file input to the server when it is changed, and disregard any other inputs until the form is submitted

I am working with a form structured like this: <form method="post" action=""> <input type="text" onchange="uploadFile()" name="username"> <textarea name="description">< ...

What is the best way to enable CSS IntelliSense for a Nuxt project?

Currently, I am undertaking a project using Nuxt.js and have set up a Docker image to manage all aspects of it. Additionally, I am looking to integrate MDBVue as a CSS library into my project. After some research, I learned that in order to utilize this li ...

Build a custom Angular2 pipe to convert JSON data into an array through iteration

I am attempting to take the JSON data provided below and convert it into an array for use with *ngFor='let item of items', which will allow me to display data as item.name, etc... This is what I have tried: var out = []; for(var key1 in object) ...

Could there possibly exist a counterpart to .cloneNode?

I'm currently working on a recipe website submission form, and I've successfully implemented code that allows me to add more ingredients dynamically. addIngredientsBtn.addEventListener('click', function(){ let newIngredients = ingre ...

Is it possible to restrict WordPress Blog archives to only display the current page?

I am currently in the process of creating a WordPress website that will feature both News and Blog sections. These sections will be on separate pages, with News and Blog posts categorized accordingly. For example, I have implemented the following code on ...

What is the process for uploading the product information to the database during checkout?

Everything on my e-commerce website is functioning perfectly, except for the checkout page. After the customer fills in the bill details, they should be able to place an order. The issue I am facing is that while I am able to retrieve and store the bill d ...

What is the best way to define a custom route in react-router-dom?

My goal is to have the URL display "/login" in the address bar when I am on the login page. // App.js <Routes> {isLoggedIn ? ( <Route path="/" element={<Root onLogout={handleLogout} />}> <Route index e ...

Update the message displayed in MUI DataTables when there are no matching records found

Whenever the data array in my MUIDataTable is empty, a default message pops up stating: "Sorry, no matching records found". I'm looking to personalize this message and input my own text. Any assistance would be greatly appreciated. ...

What is the process for converting a URL or HTML document to a PDF using the html2pdf JavaScript library?

I am working on creating a button that utilizes the html2pdf library to convert an HTML page into a PDF. Instead of selecting an element with query selector or getElementById, I would like to pass a URL because the page I want to convert is not the same as ...