Is it possible that the jQuery toggleClass fade is functioning with one class but not the other?

I'm struggling to make my i elements lose the outline class on hover. However, instead of smoothly transitioning out, the class is simply lost and added back immediately. Strangely enough, when I use the same code with a background class, it works perfectly fine. What could be causing this issue?

Another problem that I've encountered is that when attempting the transition with a background class, the background sticks around for the duration of the fade (set to 500ms) and then suddenly disappears. Ideally, it should smoothly fade out like a proper transition.

Any help would be greatly appreciated!

Check out the JSFiddle here.

$('nav a').hover(function(){
  if (!$(this).find("i").hasClass("home")){
    $(this).find('i').toggleClass('outline', 500);
    }
})

Answer №1

.hover() allows for the passing of two functions as arguments. The first function is similar to .mouseover(), while the second function is akin to .mouseout().

$('nav a').hover(function() {
  $(this).find('.home').removeClass('outline');
}, function() {
  $('.home').addClass('outline');
})

Update

You can achieve fade-in and fade-out effects using only CSS, without the need for Javascript:

nav {
    font-size: 20px;
}
nav a {
    padding-left: 30px;
}
nav a i {
    position: absolute;
    left: 0;
}
nav a i.star:not(.outline) {
    opacity: 0;
    transition: opacity 300ms ease;
}
nav a:hover i.star:not(.outline) {
    opacity: 1;
    transition: opacity 300ms ease;
}

Check out the demo here.

Answer №2

After incorporating suggestions from [Radonirina Maminiaina][1] and making some adjustments to the code myself, I was able to get it working exactly as intended.

Radonirina proposed positioning the second icon behind the original icon using position: absolute; (as shown in his code above), but then I had the idea to add the class "dark" to the hidden icon underneath and simply toggle its opacity to 0 or 1 on hover with a transition effect. This simplified the CSS and produced a beautiful result.

Many thanks once again!

Here is an example showcasing the final outcome:

$('.menu-toggle').click(function() {
  $('nav').toggleClass('nav-open', 500);
  $(this).toggleClass('open');
})
@import url('https://fonts.googleapis.com/css?family=Fjalla+One');
/* Navigation bar */

header {
  position: fixed;
  height: 50px;
  width: 100%;
  background: #666666;
}

nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

nav a {
  color: #222;
  text-decoration: none;
  text-transform: uppercase;
  font-weight: 600;
  font-size: 1rem;
  font-family: Fjalla One;
}

.smallNav {
  position: absolute;
  top: 100%;
  right: 0;
  background: #CCCCCC;
  height: 0px;
  overflow: hidden;
}

.nav-open {
  height: auto;
}

.smallNav a {
  color: #444;
  display: block;
  padding: 1.5em 4em 1.5em 3em;
  border-bottom: 1px solid #BCBCBC;
}

.smallNav a:last-child {
  border-bottom: none;
}

.smallNav a:hover,
.smallNav a:focus {
  color: #222;
  background: #BABABA;
}

/* Menu toggle */

.menu-toggle {
  padding: 1em;
  position: absolute;
  right: 1em;
  top: 0.75em;
  cursor: pointer;
}

.hamburger,
.hamburger::before,
.hamburger::after {
  content: '';
  display: block;
  background: white;
  height: 3px;
  width: 1.5em;
  border-radius: 3px;
}

.hamburger::before {
  transform: translateY(-6px);
}

.hamburger::after {
  transform: translateY(3px);
}

.open .hamburger {
  transform: rotate(45deg);
}

.open .hamburger::before {
  opacity: 0;
}

.open .hamburger::after {
  transform: translateY(-3px) rotate(-90deg);
}

.menu-toggle:hover {
  transform: scale(1.1);
}

i.icon {
  margin-right: 0.5em !important;
  font-size: 1.2em !important;
}

/* Change icons on hover */
nav a i.dark {
    position: absolute;
    left: 42px;
}
nav a i.dark {
    opacity: 0;
    transition: opacity .25s ease;
}
nav a:hover i.dark {
    opacity: 1;
    transition: opacity .25s ease;
}
nav a:hover i.outline {
opacity: 0;
transition: opacity .25s ease;
}
<!DOCTYPE html>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.1/semantic.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<header>
  <div class="header-container">

    <nav class="smallNav">
      <ul>
        <a href="#"><li><i class="icon home"></i>Home</li></a>
<a href="#"><li><i class="icon star outline"></i><i class="icon star dark"></i>Featured</li></a>
<a href="#"><li><i class="icon newspaper outline"></i><i class="icon newspaper dark"></i>News</li></a>
<a href="#"><li><i class="icon user outline"></i><i class="icon user dark"></i>Career</li></a>
<a href="#"><li><i class="icon envelope outline"></i><i class="icon envelope dark"></i>Contact</li></a>
      </ul>
    </nav>

    <div class="menu-toggle">
      <div class="hamburger">
      </div>
    </div>

  </div>
</header>

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

What causes slow performance in Asp .Net MVC? What specific steps occur between Application_BeginRequest and the start of processing the shared view?

I have come across several questions on this platform, all with responses suggesting to "set profiling and you got answer". However, I am unable to set profiling on my destination server. What happens between Application_BeginRequest and shared view proces ...

The property 'createUploadWidget' cannot be read from an undefined source

While working on a React js tutorial, I encountered an issue related to using Cloudinary React SDK for image and video uploads. Specifically, I was using the Upload Widget provided by Cloudinary and faced an error when trying to open the widget - 'Typ ...

Having difficulty grasping the concept of MVC within the context of my website's code

I'm struggling to grasp the concept of utilizing model-view-controller in the context of my registration system. As far as I understand it, the view loads, displaying the registration HTML form to the user. Once the user submits the form, a JavaScript ...

What is the best way to customize arrow designs in a React Slick Slider?

I am struggling to customize the arrows in react-slick with my own PNG images. Despite my efforts, the images appear distorted on the screen as they are automatically set to a width and height of 20px instead of their actual size of 17x27px. I have experim ...

Using Regular Expressions in Express routing

Does anyone have experience serving a file with a dynamic hash in its name on a specific route? The file is named like workbox-someHash.js and the hash changes every time the app is deployed. I attempted to serve it using the following code snippets: &qu ...

Is there a way to make a link clickable but also prevent another link from being activated when clicked?

Have you ever utilized #link to navigate to a specific section on a webpage? You can also incorporate animate and scrollTop() to ensure a smooth scroll. However, when the #link (Hash link) is situated in the navigation menu, it must be structured as exampl ...

Browser prioritizes Bootstrap over custom CSS styles

I've organized my stylesheet directory like this: stylesheets bootstrap.min.css style.css Within my style.css file, I've made adjustments to the pre tag styling: pre { background-color: #d9edf7; border: #d9edf7; color: navy ...

Issue with Web Worker functionality in SvelteKit on Firefox version 106.0.5

I've set up a function in my main file like this: const loadWorker = async () => { const SyncWorker = await import("$lib/canvas.worker?worker"); syncWorker = new SyncWorker.default(); syncWorker?.postMessage({}); ...

A stylish flyout menu with a sleek li background in jquery

Experimenting with http://tympanus.net/Tutorials/CufonizedFlyOutMenu/, I decided to remove the fly-in descriptions and am now attempting to load the extra li with a style that will "highlight" the li.current-menu-item element. An object is set up as follo ...

Sorting through an array of JavaScript objects and aggregating the step values for matching user names

Currently, I am delving into JavaScript and facing a certain challenge that may be considered easier for seasoned developers. My goal is to iterate through an array of objects, filter out objects with the same userName, and then aggregate their steps. The ...

How can I add an item to an array within another array in MongoDB?

I currently have a Mongoose Schema setup as follows: const UserSchema = new mongoose.Schema({ mail: { type: String, required: true }, password: { type: String, required: true }, folders: [ { folderName: { type: S ...

Initialize React Native project

Which ruby command shows the path to Ruby: /Users/User/.rbenv/shims/ruby Ruby -v command displays the version of Ruby installed: ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x86_64-darwin21] Which bundle command reveals the path to Bundler: /Users/Us ...

The analytics event code is visible in the source code, but is not displaying in the console

I am facing an issue with a website built on Umbraco and it has me completely stumped. I have set up event tracking for Analytics on several download buttons, and while most of them are functioning properly, there is one button causing me trouble. When I ...

Differences between .php and .html: What causes variations in IE rendering?

After duplicating one of the HTML pages in my project, I simply changed the file extension from .html to .php. Surprisingly, all browsers display the page identically except for Internet Explorer (IE), which seems to handle the pages differently based on t ...

Converting a string into an array of JSON objects

I am currently attempting to send data to my NodeJS server using the HTTP protocol (vue-resource). The goal is to send an array of JSON objects structured like this : [{"name":"Charlotte","surname":"Chacha","birth":"2000-04-02"},{"name":"Michael","surname ...

Personalizing list elements with SVG symbols

I have been experimenting with customizing the bullet points of an unordered list in HTML by using icons that I sourced from various websites. Here is the SVG code for the first icon, which is stored in home.svg: <svg xmlns="http://www.w3.org/2000/sv ...

Step-by-step guide on incorporating an additional element into the Yii radioButtonList layout

I am trying to display a radioButtonList with tooltips after each element. Here is the code I am using: <?php echo $form->radioButtonList($model, 'Field', CHtml::listData(FieldDataModel::model()->findAll(), 'id', 'name&a ...

Unable to retrieve the value stored in the global variable

I recently updated my code to use global variables for two select elements in order to simplify things. Previously, I had separate variables for values and innerHTML which felt redundant. Now, with global variables like user and group initialized at docum ...

Vuejs fails to properly transmit data

When I change the image in an image field, the new image data appears correctly before sending it to the back-end. However, after sending the data, the values are empty! Code Commented save_changes() { /* eslint-disable */ if (!this.validateForm) ...

Break up the content in table cells with a new line character

How can I get a string containing a new line character to wrap in a table cell? When I attempt to bind it, the text does not break at the new line character as expected. I have attached a screenshot for reference. In the console window, it displays correct ...