"The issue with the addClass function not properly executing within an if

I am trying to make a feature where the class changes based on my selection. The issue I am facing is that when I change it for the first time, it switches from being classified as "black" to "colored". However, upon changing it back, it remains labeled as both "black" and "colored". Can someone shed some light on why this is happening? I have already removed all existing classes upon change and called the hover() function again, which should then apply the appropriate class based on my selection. It seems to work if I uncomment the removeClass method, but I fail to comprehend why it is necessary. Thank you in advance for your help.

Here is the HTML code:

 <form>
     <select name="color">
         <option value="black-white">Black/White</option>
         <option value="colored">Colored</option>
     </select>
     <input type="checkbox" checked>Borders (on/off)
 </form>

And here is the jQuery code snippet:

function hover() {
    var color = $("select[name=color]").val();

    if (color === "black-white") {
         $("#container > div").hover(function() {
             /*$(this).removeClass("colored");*/
             $(this).addClass("black");    
         });
    } else if (color === "colored") {
        $("#container > div").hover(function() {
            /*$(this).removeClass("black");*/
            $(this).addClass("colored");
        });
    }
}

$("select[name=color]").change(function() {
    $("#container > div").removeClass();
    hover();
});

Answer №1

Event handlers cannot be nested within another event handler and expect changes. Once bound, the event handlers will remain attached to the element, even as the select options change.

You need to bind the handler only once and then evaluate the value inside it.

$("#container > div").on('mouseenter mouseleave', function(e) {
    var color = $("select[name=color]").val();

    if (color === "black-white") {
        $(this).removeClass("colored").toggleClass("black", e.type==='mouseenter');
    } else if (color === "colored") {
        $(this).removeClass("black").toggleClass("colored", e.type==='mouseenter');
    }
});
#container div { 
  height: 100px;
  width: 100px;
  position: relative;
  border: 1px solid #000;
  margin: 20px;
  color: red;
}

#container div.colored {
  background: green
}

#container div.black {
    background: black
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="color">
  <option value="black-white">black-white</option>
  <option value="colored">colored</option>
</select>

<div id="container">
  <div>Hover me</div>
</div>

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

Delete the selected background color from custom drop-down lists in versions of Internet Explorer 9 and earlier

In my asp.net application, I have a dropdown element. I am trying to remove the default blue background color that appears when the dropdown is selected, as shown in the image below. I have tried all the solutions provided in this link, but none of them s ...

The display property in CSS can be used to make a table fill out the horizontal space without

I am facing a challenge with floats inside two containers. I need the containers to wrap around the floats while maintaining a minimum height of 100% for both of them (container>another container>floats). I attempted using minimum height, however, i ...

When I click on a tab section to expand it, the carat arrows all point upwards. Only the arrows corresponding to the selected section should

click here for imageIt appears that there are four tabs, each with a click function on the carat icon. When I expand one tab, all carats point upwards instead of only the selected one appearing. accountSelection(account) { if (!this.selectedAccoun ...

Angular application's NgbTooltip positioning

Within my Angular 2/4 project, I am utilizing ng-bootstrap along with its NgbTooltip component. Consider this HTML snippet: <div class="col-sm-8 text-ellipsis" ngbTooltip="'A very long text that does not fit'" placement="top" ...

Upgrade your AngularJS Directive to an Angular 2.x+ Directive by using an HTML decorator

Is it no longer possible to utilize Angular directives as what I like to refer to as "HTML decorators"? I found this method extremely useful in Angular 1.x when transitioning legacy applications to Single Page Apps by creating a set of directives to enhan ...

Pause and continue scrolling through the page with the push of a button

I have a question about a simple demo. I am looking to prevent scrolling when button1 is clicked, and then resume scrolling when button2 is clicked. Can someone guide me on how to achieve this? Check out the Fiddle here HTML: <input type='button& ...

Slick.js integrated with 3D flip is automatically flipping after the initial rotation

I'm encountering an issue with my CSS3 carousel and 3D flipping. Whenever I navigate through the carousel and flip to the next slide, the first slide seems to automatically flip/flop after completing the rotation. You can see a visual demonstration o ...

CSS styles are missing in ASP.Net MVC4 while debugging in Visual Studio 2012

While troubleshooting my website, I noticed that the CSS is not displaying. I am encountering an Error 500 on the Site.css file when inspecting it in Firefox. My _Layout.cshtml is configured to utilize the CSS files. @Styles.Render("~/Content/css") I h ...

Utilizing Javascript to filter data across multiple columns in tables

I've been experimenting with the JavaScript code below to filter table rows. The original code is from w3schools, but I made some modifications to target all input values. It works well for filtering one column, however, when I try to input a value in ...

What are some techniques for concealing a CSS transition beneath another element in both directions?

Witness the magic in action! By clicking on the black box below, a larger black box will gracefully emerge from beneath the sidebar. While it may not be as clear in jsfiddle, rest assured that this effect is more pronounced in browsers. Thanks to some clev ...

jQuery script for reversing the collapse/expand feature

Here is a test showcasing an expand/collapse jQuery script. Currently, the div is collapsed on page load and you need to click it to see the content. Is there a way to change this so that the div is expanded on load and collapses upon clicking? <style ...

Transition smoothly with a fade-in effect as you scroll through the images, and proceed to

My Objectives: Implement a scrolling feature where images transition to the next one based on scroll movement. Create a cycle of images that automatically progress, with the view transitioning to the bottom section once all images are viewed. Currently f ...

Secret method to successfully reach a function designated within the load scope

Check out my code : <a href="javascript:void(0);" onclick="myFunction(this)">Call Function</a>​ $(window).load(function () { function myFunction(param) { console.log("called"); } }); It seems like I'm unable to access ...

Steps for incorporating 'admin-ajax.php' on the frontend

Here is the code for Javascript. Javascript used: new AjaxUpload('#upload_btn', { action: '<?php echo admin_url("admin-ajax.php"); ?>', This function only functions when the user is logged in. ...

Button not displaying box-shadow or drop-shadow effects

Why isn't the filter and box-shadow working on the button? What could be causing this issue and how can it be resolved? .desktop-modal-close-btn { position: absolute; top: 1.5rem; right: 1.5rem; height: 2.8rem; width: 2.8rem; ...

Looking for assistance with implementing mouseover scrolling on an unordered list

I am attempting to create a scrolling effect on my UL element when the mouse hovers over it, but I am having trouble getting it to work. Here is the link to my fiddle: http://jsfiddle.net/MisterStorm/4ja9apqz/3/ and here is my code: $(document).ready( ...

Adjusting the dimensions of an HTML image element in Angular dynamically

Recently, I've been exploring the idea of incorporating a jQuery BeforeAndAfter plugin into my angularJS app. However, I've encountered an issue with dynamically setting the width and height of images with different dimensions. Here's what I ...

document ready function in the Microsoft AJAX client side library

The Microsoft AJAX client-side library contains various functions that imitate the server-side Page Life Cycle and conditions like if (!Page.IsPostBack). I am unsure about which client-side function corresponds to the equivalent server-side method. What is ...

External CSS stylesheets fail to function properly in the presence of the Bootstrap framework

I'm experiencing an issue where my external stylesheet isn't being compiled when I include bootstrap. Strangely, it works fine with internal and inline stylesheets. However, when I switch to Firefox browser, it works perfectly. What could be caus ...

I am struggling to get the images aligned properly on my HTML page. Can someone please advise on how to fix this issue?

On my HTML page, I have 2 div fields. Within each field, there are 5 images listed sideways. The issue is that the images in the div below are not lining up properly side by side. Given my limited frontend knowledge, how can I align them correctly? Here&a ...