Toggle the class and execute the order within a jQuery script

When the mouse moves in, the jQuery trigger enters the status.

$(".test").bind("mouseenter mouseout", function(event) {
    $(this).toggleClass("entered");
    alert("mouse position (" + event.pageX + "," + event.pageY + ")");
  });
.entered {
    font-size: 36px;
    width: 200px;
    height: 100px;
    border: 2px solid black;
  }

  .test {
    border: 2px solid red;
    background: #fdd;
    width: 60px;
    height: 60px;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <div class="test">please move in</div>

In my code snippet, I discovered two issues:

  1. The entered status only applies font-size: 36px;, why do

    width: 200px; height: 100px; border: 2px solid black;
    not take effect?

  2. The alert pops up before $(this).toggleClass("entered"); is completed. How can I ensure that the alert executes after $(this).toggleClass("entered"); has completely finished?

Answer №1

  1. The reason for this issue is selector precedence. The rule .test in the stylesheet overrides the previous styles affecting that element because it is placed last. To resolve this, reorder the rules so that .entered comes after .test.

    For a better understanding of CSS selector specificity, refer to this helpful guide on MDN.

  2. The issue arises from alert() blocking the UI thread until dismissed. It is recommended to avoid using alert(). Instead, consider using a setTimeout() to delay the action or replace it with console.log().

Keep in mind that bind() has been deprecated and will be removed from newer versions of jQuery. Switch to using on() as a suitable alternative.

$(".test").on("mouseenter mouseout", function(event) {
  $(this).toggleClass("entered");
  console.log("mouse postion (" + event.pageX + "," + event.pageY + ")");
});
.test {
  border: 2px solid red;
  background-color: #fdd;
  width: 60px;
  height: 60px;
}

.test.entered {
  font-size: 36px;
  width: 200px;
  height: 100px;
  border: 2px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test">please move in</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

The Javascript Node class encountered an error: X has not been defined

I have a class that looks like this: const MongoClient = require("mongodb").MongoClient; const ConnectionDetails = require("./ConnectionDetails").ConnectionDetails; const Recipe = require("./recipe").Recipe; var ObjectId = req ...

Is it permissible to use DEFER or ASYNC when including a stylesheet?

I am curious if script files are able to utilize the DEFER and ASYNC keywords on a resource include. Are these keywords also compatible with stylesheet (CSS) includes? The syntax I imagine would be: <link rel="stylesheet" type="text/css" href="./path/ ...

Can the functionality of ngIf and async pipe be replicated within the component's code?

With a form component and a thank you page, I am faced with the challenge of sharing data between these two components using rxjs ReplaySubject. The full code listings can be found here. In my implementation, I am utilizing ngIf and the async pipe to hand ...

Is there a reason why Social Bar isn't appearing at the top?

My challenge is to position the bar close to the black footer. It appears correctly in Chrome, but not in Firefox and Opera. The screenshot shows how it looks in Chrome. However, in Firefox and Opera, the social bar is positioned lower and does not align ...

"Utilizing jQuery Mobile's Pagebeforeshow event with the advanced functionality of longlist

Currently, I am utilizing JQuery mobile version 1.0.1. To set up a page, the following code is utilized: <div data-role="page" id="homecomments"> <div data-role="header"> <h1>Comments</h1> <a href='#home&apo ...

The content within an iframe is inaccessible through JavaScript when the onload event occurs

My current project involves integrating a payment service provider with 3Ds, and one of the steps in the process requires following specific instructions: Upon receiving the response to your initial API request, extract an URL along with some data. Embed ...

How can you retrieve newly added DOM elements from a PartialView using Ajax.BeginForm?

Below is a snippet of code that loads a Partial View within a div element: <div id="_customerForm"> @Html.Partial("~/Views/Customer/_customerForm.cshtml", Model.customerForm) </div> The Partial View contains an Ajax Form as shown ...

planning to append the author's name to the end of the title using CSS

Here is the HTML code I have: <div class='store_detail-level1'> <span class='book_name'>How To Avoid Climate Disaster</span> <br> <span class='author_name'>Bill Gates</span> < ...

What is the reason file inputs do not trigger 'input' events, while 'change' events do fire?

Trying out a basic input: <input type="file"/> Noticing that the input event doesn't trigger when a new file is selected: $('input').on('input', function(event){ console.log('input value changed', event.targe ...

Issue with printing data consecutively using Javascript

My JavaScript code aims to display the content of the body tag again when the add button is clicked. The purpose is to add authors, with each author being added in sequence. For example, if there is only 1 author present, the user simply selects whether th ...

Ajax returns with a successful response, yet the specified action is never executed

Currently assisting with a plugin build on Wordpress and facing an issue with a basic ajax call. I am attempting to pass an object through the method 'grab_object_from_ajax_call,' but the method is not executing as expected. Below is the JavaScri ...

The significance of package-lock.json: Understanding demands vs dependencies

Within the dependency object of package-lock.json, there exist both requires and dependencies fields. For example: "requires": { "@angular-devkit/core": "0.8.5", "rxjs": "6.2.2", "tree-kill": "1.2.0", "webpack-sources": "1.3.0" }, "d ...

jQuery Validation is not functioning correctly

I am facing an issue with implementing jQuery.Validation. I have written a script and included all JS files below, but for some unknown reason, the validation always returns that the form is valid. Below is the JavaScript code I am using: $(document).rea ...

JavaScript for_each loop

Is there a way to access the field index of a JSON-Array when looping through it? I am aware that there is no foreach-loop like in PHP. This is an example of my json: { 'username': 'Karl', 'email': '<a href=" ...

Expanding rows in Angular UI-Grid: Enhancing user experience with hover functionality

Struggling to add a hover effect to the rows in an Angular UI grid. The goal is for the entire row to change background color when hovered over, but with an expandable grid that includes a row header, applying CSS rules only affects either the row header o ...

Retrieve the username from the database using PHP and then showcase it on the webpage

I've been working on pulling the username from my database and displaying it on my webpage, but I'm running into some issues. Here's the current code I have, which should work, but for some reason the $username variable is showing up as unde ...

When previewing a card on Twitter's validator tool, the image displays properly. However, when attempting to share the image on

Below is the code that I have written on my HTML page: <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:site" content="@name" /> <meta name="twitter:title" content="Twitter - image share" /> <meta name="twi ...

JavaScript error: forEach is not a function

I've encountered an issue while attempting to loop through a JSON object to extract data. Whenever I run my code, I receive this error: Type Error: element.listing.forEach is not a function. It's worth mentioning that I've used this method ...

Issues with Bootstrap's center-block functionality

I'm having trouble centering the navigation in my WordPress template that uses Bootstrap. I've tried using the center-block class on different elements, but the menu items are still aligning to the left. I even created a custom class in my custom ...

Uncaught TypeError: Cannot create new instances of User - Node.js server not recognizing User as a constructor

I encountered an issue while attempting to save a user to MongoDB database using a post request. The error message "TypeError: User is not a constructor" keeps popping up despite the straightforward setup of my code. I have double-checked but can't se ...