Troubleshooting issues with jQuery background-position animation and CSS sprites functionality

Trying to add animation to my navigation links background using a Css sprite. Check out the picture here:

$(document).ready(function(){
      $('nav a')

   // Move the background on hover

   .mouseover(function(){
 $(this).stop().animate({backgroundPosition: '0px ' +$(this).attr('data-one')+'px';}, 500);
   })

// Move the background back on mouse out

   .mouseout(function(){
  $(this).stop().animate({backgroundPosition: '0px ' +$(this).attr('data-two')+'px';}, 500);
   })
 });

This is the jQuery code that should work. Here is the HTML:

        <header id="menu">
        <h1>dawe's portfolio</h1>
        <nav>   
            <a id="m_portf" data-one="0" data-two="-37" href="#portfolio">portfolio</a>
            <a id="m_music" data-one="-72" data-two="-111" href="#music">music</a>
            <a id="m_about" data-one="-148" data-two="-185" href="#about">about</a>
            <a id="m_contact" data-one="-222" data-two="-259" href="#contact">contact</a>
        </nav>
    </header>

Tried various ways but can't figure out what the issue might be. Tried combining different codes I found, this seems close to the solution. Wondering if defining background position as absolute or relative is necessary for jQuery animations. Or maybe there are errors in the code. Please help me troubleshoot. Here is my CSS:

#m_portf{
background: #fff url('menu.png')repeat-X 0px -37px;
}
#m_music{
background: #fff url('menu.png')repeat-X 0px -111px;
}
#m_about{
background: #fff url('menu.png')repeat-X 0px -185px;
}
#m_contact{
background: #fff url('menu.png')repeat-X 0px -259px;
}

Answer №1

To create an animation for background image position, you will need to utilize the "jquery.backgroundpos.js" plugin. You can acquire this plugin from the following link:

The code below demonstrates how to achieve the desired effect:

CSS

body{
    background-color:#ccc;  
}
nav a{
    background-image:url(http://img689.imageshack.us/img689/2996/menufc.png);
    display:block;
    width:120px;
    height:22px;
    margin-bottom:10px;
}
#m_portf{
background-position:0 -37px;
}
#m_music{
background-position:0 -111px;
}
#m_about{
background-position:0 -185px;
}
#m_contact{
background-position:0 -259px;
}

JQuery

$(document).ready(function(){
$('nav a').hover(
function () {
    $(this).addClass('active');
    $(this).stop().animate({backgroundPosition: '0px ' +$(this).attr('data-one')+'px'}, 500);
},
function () {
    $(this).removeClass('active');
    $(this).stop().animate({backgroundPosition: '0px ' +$(this).attr('data-two')+'px'}, 500);
}
);
});

Html

<header id="menu">
<h1>dawe's portfolio</h1>
<nav>   
    <a id="m_portf" data-one="0" data-two="-37" href="#portfolio">portfolio</a>
    <a id="m_music" data-one="-72" data-two="-111" href="#music">music</a>
    <a id="m_about" data-one="-148" data-two="-185" href="#about">about</a>
    <a id="m_contact" data-one="-222" data-two="-259" href="#contact">contact</a>
</nav>
</header>

You can view the working demo file by clicking on this Link

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

How can CSS be used to print multiple pages without any margins? And what is causing this slight extra height in the output

Check out the Live Demo here, apologies for the messy CSS as I have been experimenting with different styles. I am currently attempting to print PDF files using the browser's print dialog. Each file consists of 4 pages in the DIN lang format with an ...

Troubles encountered when cascading val(), text(), and data()

Here is my JavaScript/jQuery code: $select.append($("<option />") .val(this.id) .text(this.text) .data('name', this.name) .data('isstorage', this.isstorage)); Although it successfully assigns values to t ...

Is there a way to use jQuery to adjust the text color once it has been clicked on?

I have been struggling to change the text color upon clicking on it without any success. Within my code, there are seven labels - one for the question, four for the answer options, one for the correct answer, and the last one for the explanation. The desi ...

Is there a way to create an effect where the color of a floating action button changes when you hover over it, similar to a filter?

I'm new to using the <Fab /> element and I'm struggling to figure out how to implement a hover effect that will change the button's color. Here's what I have so far: JavaScript: <Fab variant="extended" className=&quo ...

Tips for showcasing additional choices within a SELECT element while incorporating floating labels and adjusting the size

I'm struggling to make a floating label work smoothly with an HTML select that has a size="5" attribute using Bootstrap 5.3.x. It seems like it's not possible without some hacks or missing information from the Bootstrap documentation. According ...

NodeJS and Express server is having trouble accessing the linked JavaScript file(s) from the HTML document

I'm facing a challenge with my web hosting server on AWS while using express.js. I have encountered the following error: root@ip(censored):/home/ubuntu/(censored)# /home/ubuntu/(censored)/routes/index.js:15 $(document).ready(function() { ^ Referen ...

Incorporating React's dynamic DIV layout algorithm to generate a nested box view design

My goal is to showcase a data model representation on a webpage, depicting objects, attributes, and child objects in a parent-child hierarchy. I had the idea of developing a versatile React component that can store a single data object while also allowing ...

Adjust the width and height of the span to encompass more than just the content within it

I'm struggling to apply height and width to empty spans using CSS, but the span only fills its content <div class="container"> <div id="widgets-container"> <span class="widget" name="widget1" style="background-col ...

Identify which browsers are compatible with HTML5 video autoplay detection

Having completed several projects with video backgrounds that autoplay when the page loads, I have encountered issues with mobile browsers not supporting the autoplay attribute on HTML5 videos. In these cases, an image is loaded instead of the video. To d ...

Utilizing values from .properties files in Java with Spring for internationalization: A straightforward approach to handle Strings

Here is the code snippet I am using: @Value("${app.user.root}") private String userRoot; This code helps me to fetch a constant value from my application.properties file. Within my GetMapping method, I need to redirect to the error page and pass a S ...

"Efficiently Triggering Multiple Events with One Click in JavaScript

Hey everyone, I could use some assistance. I'm trying to execute multiple events with a single click. Currently, I can change the image in my gallery on click, but I also want to add text labels corresponding to each image. Whenever I click on a diffe ...

jQuery registers the enter event, but does not proceed to trigger the enter action

Hey there, I've been experimenting with jQuery to capture the enter event. Something peculiar is happening though - after pressing enter in the text area, an alert pops up but the text gets entered only after that. Despite trying various solutions, I ...

Change the input value by clicking different buttons

Looking for a way to change the value or source of an input when clicking on different buttons? For example, clicking on Button 1 changes the input to "apple" and Button 2 changes it to "orange", etc. Here is a snippet of what I have tried so far: $(doc ...

The Tab style in Mobile Angular UI does not get applied correctly when nested within an ng-repear

While working on a tabbed control with mobile-angular-ui (), I encountered an issue when trying to generate the tabs dynamically. Initially, everything looked good with the following code: <ul class="nav nav-tabs" ui-state='activeTab' ui-def ...

I am dynamically generating table rows and populating them with data. However, I encountered an issue with retrieving the data by their respective IDs

Creating a table row dynamically by populating it with data. However, encountering an issue with retrieving the data by their respective id. if(xmlhttp.status == 200) { var adminList = xmlhttp.responseJ ...

In JavaScript, use the following code to replace "(" with "(":

Is there a way to dynamically transform the string "Test(5)" into "Test\(5\)" using JQuery or Javascript? I attempted this approach, but it did not work as expected var str = "Test(5)"; str = str.replace("(","\("); str = str.replace(")"," ...

What is the best way to incorporate the value of a textbox into a list?

I currently have a list structured like this: <p>Please choose from the following options:</p> <script type="text/javascript"></script> <select id='pre-selected-options1' multiple='multiple'> <opt ...

What steps can I take to ensure that my initial Ajax Get request is completed before proceeding with the next one?

Having two methods that return promises is not enough. I am attempting to make the second method execute only after the first one has obtained and manipulated data, but I have struggled to find a solution despite others asking this question before me. Here ...

The bullets in the HTML unordered list are partially hidden from view

My unordered list is experiencing issues with displaying bullets correctly. In Firefox and Internet Explorer, the bullets are only partially shown, while in Chrome they are not visible at all. Adding margin-left: 5px to the <li> element resolves this ...

The thumbnail image is failing to load, and when I hover over an image, it moves upwards

I seem to be encountering an issue with a website I uploaded for testing. Everything appears to be working correctly when checked locally in Dreamweaver CS6. However, once the site is uploaded, some issues arise. When hovering over the images, a problem is ...