Jquery's Conditional Statements: If/Else

JSFiddle

I am working on a navigation filter that highlights projects based on their respective categories when clicked. I want to make it so that when the #all-btn is clicked, all items are highlighted in their designated colors. Currently, they are set to highlight in black, but I would like to change this to:

  • Graphic design - green
  • Web design - red
  • Flat design - blue

I believe using an if/then statement in jQuery could accomplish this, but I'm unsure of how to implement it. For example:

if (the item has class graphic) { 
    $("#projects").find("li.graphic").toggleClass("highlight-graphic");
} 
else if (item has class web) {
    $("#projects").find("li.web").toggleClass("highlight-web");
} 
else {
    $("#projects").find("li.flat").toggleClass("highlight-flat");
}

What would be the best approach to achieve this and will this code work effectively?

Answer №1

If you want to add custom attributes to your tab elements, consider using data-* attributes such as data-target.

<ul>
    <li class="default-btn" data-target="wrap" id="all-btn">All</li>
    <li class="default-btn" data-target="web" id="web-btn">WEB DESIGN</li>
    <li class="default-btn" data-target="graphic" id="graphic-btn">GRAPHIC DESIGN</li>
    <li class="default-btn" data-target="flat" id="flat-btn">FLAT DESIGN</li>
</ul>

You can then simplify your jQuery code like this:

$('li.default-btn').on('click', function () {
    $('#projects').find('.' + this.dataset.target).toggleClass('selected');
});

To make it even simpler, adjust your CSS accordingly:

Check out the updated version here

.web.selected {
    border: 3px solid red;
}
.graphic.selected {
    border: 3px solid green;
}
.flat.selected {
    border: 3px solid blue;
}

Answer №2

To perform the action, follow these steps:

$('li#all-btn').click(function () {
    var toggle = $('#projects .wrap').not('.highlight-web, .highlight-graphic, .highlight-flat').length > 0;
    $("#projects").find("li.web").toggleClass("highlight-web", toggle);
    $("#projects").find("li.graphic").toggleClass("highlight-graphic", toggle);
    $("#projects").find("li.flat").toggleClass("highlight-flat", toggle);
});

See a demonstration here: Fiddle


If you simply want to toggle the class, use this code:

$('#all-btn').click(function () {
    $("#projects").find("li.web").toggleClass("highlight-web");
    $("#projects").find("li.graphic").toggleClass("highlight-graphic");
    $("#projects").find("li.flat").toggleClass("highlight-flat");
});

Check out the demo here: Fiddle

Answer №3

To check if an element has a certain class using jQuery, you can utilize the hasClass() method. Here is an example:

var projElement = $("#projects li");

if ( projElement.hasClass('graphic') ) { 
    projElement.toggleClass("highlight-graphic");
} 
else if (projElement.hasClass('web') ) {
    projElement.toggleClass("highlight-web");
} 
else if (projElement.hasClass('flat') ) {
    projElement.toggleClass("highlight-flat");
} 
else {
    // do nothing;
}

UPDATE

I made some changes to your code in this updated fiddle. I removed console logging that was just for illustration purposes:

$(document).ready(function () {
    $('#nav-filter li').on('click', function () {
        var clickedOn = $(this).attr('id');
        console.log( 'clicked on: ' + clickedOn ) ;

        $("#projects li").each(function (index, value) {
            if (clickedOn === 'all' ){
                $(value).toggleClass("highlight-" + clickedOn );

            } else if ($(value).hasClass( clickedOn )) {
                $(value).toggleClass("highlight-" + clickedOn );
            }
        });
    });
});

Check out the documentation here

Answer №4

Consider utilizing jQuery's hasClass() method:

if ($('#item').hasClass('graphic')) { 
  $("#projects").find("li.graphic").toggleClass("highlight-graphic");
}

OR

An alternative approach is to use toggleClass():

$("#projects").find("li.graphic").toggleClass("highlight-graphic", $('#item').hasClass('graphic'));

In this scenario, the highlight-graphic class will be added if the item contains the class graphic, otherwise it will be removed.

Answer №5

While jQuery can be used, achieving the same result is actually much simpler with just CSS.

$(".graphic, .web, .flat").toggleClass("highlight");
.graphic, .web, .flat {
  color: white;
 }

.graphic.highlight {
  color: red;
}
.web.highlight {
  color: green;
}
.flat.highlight {
  color: blue;
}

Answer №6

To streamline your code, try eliminating all if else statements and utilize the following snippet:

The currentClass variable may correspond to options like graphic, web, or list.

Revise the function as follows to dynamically change classes: $(document).find("li." + currentClass).toggleClass("highlight-" + currentClass);

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

"Stay up-to-date effortlessly with the latest information on ext.data.store through automatic

I am working with an ExtJS data store mystore= Ext.create('Ext.data.Store', { id: 'store_id', fields: ['label', 'value', 'id', 'type'], autoLoad: true, proxy: ...

How to utilize Jquery to return two variables into separate div elements from a single php file

Do you know how to display the values of two variables in separate div elements using Jquery and just one php file? PHP <?php $variable1 = "10"; $Variable2 = "20"; echo $variable1; echo $variable2; ?> Jquery $("#id").on("change", function() { var ...

Designing a layout for a chat application that is structured from the bottom up

I'm currently in the process of designing a web application for a chat platform. I have access to an API that provides a list of messages: chatsite.com/api/thread/1/messages/ [ { "id": 2, "sender": { "id": 2, ...

Is there a way to display two words side by side in React components?

I previously had the following code: projectName: project.get('name') === 'default' ? 'No Project' : project.get('name') In the render() method, it was written like this: <div className='c-card__projects&ap ...

Issues with Pagination in a Dynamic Grid System when using Bootstrap DataTables

I am trying to display a user list in a grid format. Below are my PHP codes: Here is a simple PHP array: <?php $aso_arr = array( "1"=>"1", "2"=>"2", "3"=>"3", "4"=>"4", "5"=>"5", "6"=>"6", "7"= ...

Adjust the width of a div element to match its content when nested within another div element

I am looking for a solution in the provided code snippet where the width of the .content div can automatically adjust to fit the .product divs inside it. It is important that the width adjusts dynamically as there could be different numbers of products an ...

Color Coding Groups Using Google Charts

I have a need to generate a chart that is grouped by 7 records or bars. I have already set it up, but now I want to add a background color for each group. I attempted using chartArea: {width: '100%', backgroundColor: 'silver'} and backg ...

MailChimp's Ajax form submission fails to successfully add new subscribers to the mailing list

Seeking help to integrate MailChimp subscription with ajax using this method. The form appears to be functioning correctly, displaying error messages as expected along with the "submitting..." and confirmation message. However, new subscribers are not bein ...

How can you create an accordion menu that expands when a button is clicked?

Is there a way to make an accordion menu open when the 'More' button is clicked? I've tried, but it always starts in its expanded state and collapses when the button is clicked. What I really want is for the accordion to be closed initially ...

Can Keyboarddatepicker automatically format the date?

We are utilizing material ui Keyboarddatepicker in our React application and have specified the date format using props as format=DD/MMM/YYYY, resulting in dates being displayed like "10/12/2020". The date picker functions perfectly when selecting a date. ...

Ensure that the collapsing toggler and the textbox are aligned on the same line

As part of my project, I am developing a bootstrap5 website that features a search form. I am facing an issue where I am unable to align the form text box labeled "search by country" vertically on the same line as the collapsible hamburger toggler. I hav ...

Managing the scrolling direction horizontally with waypoints.js

As I work on creating a custom wizard form with waypoints, I've encountered an interesting issue that has left me puzzled. In my sample CODEPEN, you can see two pages of the wizard process to better understand the problem. Upon clicking the forward ...

Displaying a Bxslider inside a modal window

Attempting to launch a popup div that will include a bx slider. The link triggering the popup div works correctly. However, the images inside the bxslider are not displaying, even though the loading and direction control images are visible. Initially thoug ...

Low-quality CSS Gradient Design

Hey everyone, Feel free to take a look at my preloader on this link: (Hit ESC as soon as the page loads to pause the website and focus on the loader) Upon closer inspection, you'll notice that there is an issue with the quality of the background l ...

jquery tutorial: toggling attributes

Is there a way to switch between two images when a user hovers over a div? I was thinking of using a boolean flag that gets updated every time the div is hovered over, and then using this flag to toggle the images. Can someone please confirm if this approa ...

Utilizing AJAX to submit a combination of text fields and files in an HTML form

Just starting out with AJAX and JQuery, I'm curious if it's possible to send data from an HTML form, including a text file and two separate text boxes, via an AJAX request. So far, I've managed to send the data from the text boxes but not th ...

Angular - custom font styles for ui grid

I recently added "angular" and "angular-ui-grid" to my app and made sure to include the necessary files: angular.min.js ui-grid.min.js ui-grid.min.css Although the table is displaying properly, the arrows in the row header show up as "Korean symbols." D ...

Menu bar placed atop a carousel

I am currently in the process of developing a website and I have encountered an issue with the navigation bar. I have a slider that I would like to appear below the navbar but the navbar is pushing it down instead. Ideally, I want the navbar to be transpar ...

I aim to customize the options of a dropdown list based on the selection of another dropdown

I am looking for a way to dynamically filter employees based on the department selected. Unfortunately, my knowledge of JavaScript and Ajax is limited. <div class="pure-checkbox ml-15"> <input id="checkbox2" name="sta ...

A way to verify a datalist field using jQuery validator within a PHP environment

Greetings, I currently work as a web application developer and I am facing an issue with jQuery validation. I have a form where I need to display a list of employees using the `datalist` tag. The client should be able to enter a correct name or select an e ...