Having trouble with this code// Does anyone know how to make the div slide in line with other divs when hovering over it?

After spending countless hours analyzing and trying various solutions, I have come to the realization that I need to seek help with my code. The task at hand is proving to be incredibly frustrating, and I have exhausted all other options before resorting to asking for assistance here.

My objective is to create a header with a sliding bar effect above each menu item on hover. A perfect example of what I am aiming for can be seen on . If you visit the site and move your mouse over the navigation bar, you will immediately understand the desired outcome.

Below is the snippet of my current code...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
div {
    display: inline-block;
    float:left;
}
#red {
    background-color:#FF0000;
    height:100px;
    width:100px;
}

#blue {
    background-color:#0000FF;
    height:100px;
    width:200px;
}

#yellow {
    background-color:#E2BE22;
    height:100px;
    width:50px;
}

#green {
    background-color:#008800;
    height:100px;
    width:170px;
}
#slider{
    background-color:#6FF;
    height:10px;
    width:100px;
    position:relative;
}
</style>
</head>

<body>
<div id="slider"></div><br />
        <div id="red"></div>
        <div id="blue" onmouseover="javascript:movetoblue()" onmouseout="javascript:exitblue()"></div>
        <div id="yellow" onmouseover="javascript:movetoyellow()" onmouseout="javascript:exityellow()"></div>
        <div id="green" onmouseover="javascript:movetogreen()" onmouseout="javascript:exitgreen()"></div>
</body>
</html>
<script>
var slider = document.getElementById( 'slider' );

function movetoblue(){
        var slider = $("#slider");  
        slider.animate({left: '100px', width: '160px'}, "slow");
}
function exitblue(){
        var slider = $("#slider");  
        slider.animate({left: '7px', width: '200px'}, "slow");
}
function movetoyellow(){
        var slider = $("#slider");  
        slider.animate({left: '100px', width: '160px'}, "slow");
}
function exityellow(){
        var slider = $("#slider");  
        slider.animate({left: '7px', width: '200px'}, "slow");
}
function movetogreen(){
        var slider = $("#slider");  
        slider.animate({left: '100px', width: '160px'}, "slow");
}
function exitgreen(){
        var slider = $("#slider");  
        slider.animate({left: '7px', width: '200px'}, "slow");
}
</script>

I acknowledge that there might be errors in the code provided. Any assistance or guidance on improving it would be greatly appreciated. Thank you :)

PS: While I aim for this functionality to work smoothly across Chrome, IE, Safari, and Firefox, my primary concern is ensuring compatibility with Chrome, IE, and Safari. Once again, thank you for any help!

Answer №1

It seems like you are utilizing jQuery incorrectly. I have prepared a JSFiddle for your reference, please check out this

Update 1:

I have optimized the code by including the following for better performance:

$("#slider").stop()

$(document).ready(function() {
  $("#slider").animate({
      "left": $(".item:first").position().left + "px",
      "width": $(".item:first").width() + "px"
    }, 0);
  
  $(".item").hover(function() {
    $("#slider").stop()
    $("#slider").animate({
      "left": $(this).position().left + "px",
      "width": $(this).width() + "px"
    }, 500);
  });
});
div {
  display: inline-block;
  float: left;
}
#red {
  background-color: #FF0000;
  height: 100px;
  width: 100px;
}
#blue {
  background-color: #0000FF;
  height: 100px;
  width: 200px;
}
#yellow {
  background-color: #E2BE22;
  height: 100px;
  width: 50px;
}
#green {
  background-color: #008800;
  height: 100px;
  width: 170px;
}
#slider {
  background-color: #6FF;
  height: 10px;
  width: 100px;
  position: absolute;
  left: 0;
  top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slider"></div>
<div id="red" class="item"></div>
<div id="blue" class="item"></div>
<div id="yellow" class="item"></div>
<div id="green" class="item"></div>

Update 2:

To set the initial position, replace this section:

$("#slider").animate({
      "left": $(".item:first").position().left + "px",
      "width": $(".item:first").width() + "px"
}, 0);

With this:

$("#slider").animate({
      "left": $("#TAG_ID").position().left + "px",
      "width": $("#TAG_ID").width() + "px"
}, 0);

NOTE TAG_ID refers to the id property of your starting div

Update 3:

If the user fails to select a tab:

$("#slider").delay(3000).animate({
    "left": $(this).position().left + "px",
    "width": $(this).width() + "px"
}, 500);

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

Prevent further triggering of the .click function when the user clicks repeatedly

Is there a way to prevent the .click function from executing if the user clicks too many times? This is my current code: $('button').click(function() { $('#bg').fadeToggle('200'); }); Check out the jsfiddle DEMO ...

Is your MJML column layout not stacking properly on mobile devices?

I've been struggling with a basic 2-column design created using the online editor at mjml.io. I can't seem to get it to stack on mobile devices. The email looks identical on desktop (Outlook 365 for PC) and mobile (Outlook for iOS on iPhone 13) ...

Node.js server for Cross-Origin Resource Sharing

I'm brand new to Node.js and I'm trying to run some example code, but I keep encountering CORS issues. Server.js var http = require('http'); var io = require('socket.io'); server = http.createServer(function(req, r ...

React JS makes it simple to create user-friendly cards that are optimized

I have a collection of objects that include a name and description. The name is short and consists of only a few characters, while the description can vary in length. I am looking to showcase this data within Cards in my React project, and have tried using ...

Are there any class options that offer a wider width than modal-lg?

I am currently using vue.js along with Bootstrap. Within my modal dive, I am looking for a class that will help me increase the width of the modal div, As you can see from the image below, my modal div looks like this. I plan on adding 12 more tabs, whic ...

Is it more effective to consolidate similar styles into a single class and utilize it, or is it better to go the opposite route?

Which code snippet below is more efficient? First Example .a { color: #000; width: 20px; -webkit-transition: 0.3s all; -moz-transition: 0.3s all; -o-transition: 0.3s all; transition: 0.3s all; } .b { color: #333; width: 40px; -webkit-transition: 0.3s a ...

Unable to trigger click event on dynamically added element using Chrome (jQuery)

My approach here involves dynamically creating a drop-down and binding the click event to the <option> within the <select> var $select = $('<select></select>'), $option1 = $('<option>a</option>') ...

Retrieving the Short Date Format from the user's device or browser within a React application

Currently, I am in the process of utilizing reactjs along with material UI datepicker. My objective is to transmit the short date format to the datepicker component, such as format="MM/dd/yyyy". In addition, I wish to employ the pre-existing date ...

Dealing with Vue's performance problems when using input type color and v-model

I am encountering a problem with setting the v-model on an input of type color. Whenever I change the color, there is a noticeable drop in frame rate and the application's FPS spikes from 60 to 3. You can see it reflected in the Vue performance graph ...

Guide to organizing the sequence of text in HTML and CSS

Seeking guidance on reordering text and adjusting spacing on my website. Below, I have attached an image where I intend to change the sequence of text and modify the spacing accordingly. I aim to switch the order from "Resume About Work" to "Work About Re ...

What is the proper way to utilize $apply and $watch in the Angularjs 1.4.10 Directive Structure?

`.directive('counter', function counter() { return { scope: {}, bindToController: { count: '=' }, controller: function () { function increaseCount() { this.count++; } function decreaseCo ...

Adding hyperlinks to images on a Project Page in Squarespace with the help of JQuery

I'm currently creating a website on Squarespace and facing a challenge with the project pages. While Squarespace allows me to add images with titles and descriptions, I do not have direct access to edit the page. Unfortunately, the platform does not h ...

Error in defining class variable within the constructor not found

Just started delving into CoffeeScript and facing a challenge. In my code snippet below, I initialize WebSocketServer with a number as the first argument and a function as the second argument. However, when the websocket receives a message, @msgHandler sud ...

Configure the input to accept integer values

This page that I have developed is designed for entering Latitude and Longitude values. <div class="container "> <form class="entry"> <div class="aligncenter"> <h5 style="color:MediumTurquoise; font ...

Tips for storing mustache templates for rendering in Node.js

My data is stored in the following format: let data = {"list" :[ { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98f9fafb8afef0f9f5e8f4fdb6fbf7f5">[email protected] ...

A linear gradient effect originating from the center/middle of the background

Is it possible to create a linear-gradient background that starts from the center or middle of the screen? This is the CSS I am currently using: body { display: table; width: 100%; height: 100%; margin: 0 auto; background-repeat: no-r ...

The primary container is brimming with an abundance of content

Can anyone help me with a CSS issue I'm experiencing in the latest versions of Chrome and Firefox? I can't seem to figure it out on my own. The problem arises with a container div that has a 50px top margin. Inside this container, there's a ...

The behavior of the jQuery done() function appears to be triggering prior to the request being

I have encountered an issue where an ajax loader is not hiding after a request is done. The problem is that the done() callback is firing immediately after the blur() event, even before the request is sent. To confirm this, I intentionally delayed the re ...

Error in Node.js: Attempting to modify headers after they have already been sent to the client

I've been facing the challenge mentioned in the topic for quite some time now. Is there anyone who can assist me with this? Feel free to ask any questions if you need clarification. I've gone through a few potential solutions for this issue, but ...

Various web browsers may exhibit varying behaviors when processing extremely lengthy hyperlinks

I am curious to understand why browsers handle long URLs differently based on how they are accessed. Let me explain further: Within my application, there is a link to a specific view that may have a URL exceeding 2000 characters in length. I am aware that ...