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 the cursor from exiting the div element when the tab key is pressed

Currently, I have implemented a search input box allowing users to either enter a value or select from a list of suggestions. The issue arises when the user selects an option using the tab key, as it causes the cursor to move outside the input box despite ...

Submitting a form within AJAX-powered tabs (using the Twitter Bootstrap framework)

I have encountered an issue while trying to submit a form that is located within tabs. The content of these tabs is generated through AJAX. My problem arises when I submit the form - the page refreshes and loads the "default" tab, causing the PHP function ...

Separate compound words without hyphens at the boundaries of each word

I am currently incorporating the use of Bootstrap for my project. Let's assume that I have text displayed in this way: "Stackoverflow" Is there a method to automatically ensure that it breaks like below if the text exceeds the container: "Stack ...

Maintain the collapsing of links in the navbar with the help of Bootstrap

Currently, I am designing a responsive navigation bar utilizing Bootstrap. The current layout displays as follows: in expanded view, and: in collapsed view. While the design appears satisfactory in normal view, I am looking to maintain the "Sign Up" lin ...

Finding the final day of a specific year using the moment library

When it comes to determining the last day of a year, hard-coding the date as December 31st seems like a simple solution. While there are various methods using date, js, and jquery, I am tasked with working on an Angular project which requires me to use mom ...

The setStyle() method in JavaFX is like CSS Selectors

Is it possible to bind CSS files to style JavaFX components and also change properties dynamically in code? I'm struggling with the setStyle() method as there's limited documentation available on how to use it effectively. Instead of modifying t ...

Merge data from api into visual charts using Google Chart Library

I received an API response with the following data structure: { "status": 200, "message": "OK", "data": [ { "_id": { "report_type": "robbery" }, "report_type": "robbery", "Counts": 11 }, { "_id": { "repo ...

Add the word "String" in front of the moment timestamp

In my project, I have used React along with Material UI to show the message Running check... when the clicked state is set to true. If it's not true, then I am displaying a timestamp by utilizing the react-moment library. <Typography gutterBottom ...

Calculating and displaying the output on an HTML page: A step-by-step guide

Within my HTML, I have two values stored in Session Storage: "Money" and "Time". These values are based on what the user inputted on a previous page. For example, if someone entered that they need to pay $100 in 2 days. My goal is to generate a list that ...

I have noticed that the SVG viewBox appears different when using Vue.js

I cannot wrap my head around the fact that my svg viewBox acts differently in html compared to vuejs. Here is my code in vue: <template> <div class="venuecontainer" style="background-color:#808040;"> <svg class=&quo ...

Display two examples from the material-ui documentation

My goal is to merge two demos found in the material-ui documentation. Clipped under the app bar - Describes a page layout Fixed header - Illustrates a table with a fixed header. I am looking for a solution where the table occupies the entire available p ...

What is the best way to modify part of a URL and refresh the page with the updated changes?

Good evening, everyone. This is my inaugural post on this platform, so I hope I am following the norms correctly. I have scoured various sources, including this site, in search of a solution to a problem I am facing, but I have not come across anything t ...

How can I detect if the browser's built-in object is available in Angular?

Exploring the Wechat JS API: The Wechat JS API relies on the WeixinJSBridge object within the Wechat built-in browser. This object is not immediately available upon opening the WebView; the client-side needs to initialize it. Once the WeixinJSBridge object ...

Certain characters are absent from the text

Within an html table, I've compiled a list of camera names. Should you wish to make any edits, simply click on the edit button provided. Upon clicking the edit button, a form will open up along with various other options, allowing you to change the n ...

"Vue component inputs fail to update when used in the same instance

I have reused the same component in both the navigation menu and on the people's page. My problem is that when the SearchComponent inputs in the navigation update their values, the SearchComponent inputs on the people's page do not update, and v ...

"Mastering the Art of Combining Two AJAX Requests Seamlessly (Without the Need for Plugins

I currently have 2 distinct ajax requests: One for endless loading The other for product filtering - by size, color, orderby, and it functions correctly with pagination. However, after applying the filters, the loadmore script does not work as expecte ...

Sorting table tbody elements created dynamically with JavaScript on an npm webpack application is not possible with jQuery UI

My JS-built table is populated with data from a JSON file fetched after a request. I want to be able to drag and drop these tbodys and update the JSON file accordingly. To handle sorting, I decided to use jquery-ui. While .sortable() works well for drag a ...

Removing the empty option in a select element with ng-model

There's a situation I'm dealing with that involves a select dropdown along with a refresh button and a plus button. The issue arises when clicking the refresh button sets the model to null, while clicking the plus button displays the dropdown wit ...

Position the personalized radio button to be in line with the first choice text

I frequently update this section with a new Jsfidle link to demonstrate the issue when the max-width is set to 300px. For responsive design, adding the "span" tag before radio buttons helps align input content with custom checkbox backgrounds. To see the ...

Is there a way to get this reducer function to work within a TypeScript class?

For the first advent of code challenge this year, I decided to experiment with reducers. The following code worked perfectly: export default class CalorieCounter { public static calculateMaxInventoryValue(elfInventories: number[][]): number { const s ...