Modifying Image Source on Hover Using Jquery

Is it possible to change the source of an image on hover and then back to the original source? For example, the name of the file always remains the same, but the number changes - 1 for the original and 2 for the hover. Thank you for any advice.

Code:

<ul class="nav navbar-nav">
    <li><a href="#">Featured</a></li>
    <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Meet ATS<b class="caret"></b></a>
            <ul class="dropdown-menu meet-ats-top">
            <li><a href="#"><img src="/images/google1.png"></a></li>
            <li><a href="#"><img src="/images/in1.png"></a></li>
            <li><a href="#"><img src="/images/youtube1.png"></a></li>
            <li><a href="#"><img src="/images/facebook1.png"></a></li>
            <li><a href="#"><img src="/images/twitter1.png"></a></li>
            </ul>
     </li>
</ul>

Answer №1

Experiment

jQuery(function ($) {
    $('.meet-ats-top li').hover(function () {
        $(this).find('img').attr('src', function (i, src) {
            return src.replace('1.png', '2.png')
        })
    }, function () {
        $(this).find('img').attr('src', function (i, src) {
            return src.replace('2.png', '1.png')
        })
    })
})

Alternatively

jQuery(function ($) {
    $('.meet-ats-top li').hover(function (e) {
        $(this).find('img').attr('src', function (i, src) {
            return src.replace(/(\d+)(?=\.)/, function (val) {
                return e.type == 'mouseenter' ? 2 : 1
            })
        })
    })
})

Answer №2

If you want to give it a shot, consider implementing this:

$(".dropdown-menu li a img").hover(function(){
   $(this).attr('src', $(this).attr('src').replace('1','2'));
}, function (){
   $(this).attr('src', $(this).attr('src').replace('2','1'));
})

Give it a try and see if it does the trick!

Answer №3

Check out the jQuery method called Hover:

http://api.jquery.com/hover/

Alternatively, you can achieve the same effect using CSS and the :hover pseudo-class

How to use the 'hover' pseudo-class in CSS

Answer №4

Creating this with CSS is the way to go.

Here's the HTML:

 <ul class="dropdown-menu meet-ats-top">
   <li><a href="#" class="google"></a></li>
        ...
 </ul>

Now for the CSS:

.google {
    background-image: url(/images/google.png);
    >>Remember to specify width and height based on the Image
}
.google:hover {
    background-image: url(/images/google1.png);
}

UPDATE:

Since an empty a-Tag has no dimensions, you need to include another div/span inside:

<li><a href="#" class="google">**<span></span>**</a></li>

And update the CSS like this:

.meet-ats-top a span { width: XYpx; height: XZpx; }

Answer №5

$('.dropdown-menu').on('mouseover', function(){
    var imageSrc = $(this).find('img').attr('src');
    var temp = imageSrc.split('.');
    var newSrc = imageSrc.substr(0, temp[0]-1);
    $(this).find('img').attr('src', newSrc + '2.' + temp[1]);
});

Fingers crossed that this solution does the trick!

Answer №6

1. Optimal CSS Approach

Utilize CSS sprites by combining all social icons into a single file and positioning them using background-position. This method allows for all icons to be downloaded in one HTTP request.

2. Alternative CSS Technique for Images

Embed all images in the HTML and hide them using CSS:

<li>
     <a href="#">
        <img src="/images/google1.png">
        <img src="/images/google2.png">
     </a>
</li>

Apply the following CSS:

.dropdown-menu a img {
    display: none; // hides all images
}

.dropdown-menu a img:first-child {
    display: inline-block; // shows the first child image
}

.dropdown-menu a:hover img {
    display: inline-block; // shows all images on hover
}

.dropdown-menu a:hover img:first-child {
    display: none; // hides the first image on hover
}

Answer №7

Implementing JavaScript:

<a href="INSERT TARGET URL"><img src="INSERT URL OF FIRST IMAGE" onmouseover="this.src='INSERT URL OF SECOND IMAGE'" onmouseout="this.src='INSERT URL OF FIRST IMAGE'" /></a>

Here is an example:

<ul class="nav navbar-nav">
<li><a href="#">Featured</a></li>
<li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Meet ATS<b class="caret"></b></a>
        <ul class="dropdown-menu meet-ats-top">
        <li><a href="#"><img src="/images/google1.png" onmouseover="this.src='/images/google2.png'" onmouseout="this.src='/images/google1.png'" ></a></li>
        <li><a href="#"><img src="/images/in1.png" onmouseover="this.src='/images/in2.png'" onmouseout="this.src='/images/in1.png'"  ></a></li>
        <li><a href="#"><img src="/images/youtube1.png" onmouseover="this.src='/images/youtube2.png'" onmouseout="this.src='/images/youtube1.png'"  ></a></li>
        <li><a href="#"><img src="/images/facebook1.png" onmouseover="this.src='/images/facebook2.png'" onmouseout="this.src='/images/facebook1.png'"  ></a></li>
        <li><a href="#"><img src="/images/twitter1.png" onmouseover="this.src='/images/twitter2.png'" onmouseout="this.src='/images/twitter1.png'" ></a></li>
        </ul>
 </li>

Answer №8

Give this code snippet a try:

<div class="image-hover">
 <img src="images/design-1.png" />
</div>

$(function() {
  $(".image-hover").hover(function() {
  $(this).find('img').attr("src", "images/design-2.png");
    }, function() {
  $(this).find('img').attr("src", "images/design-1.png");
    });
  })

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's the best way to mount a file on a field?

Can you assist in resolving this issue by utilizing a form on JSFiddle? If a user fills out the following fields: name, email, phone, message The data should be output to the console. However, if a user adds a file to the field attachment No output ...

Scouring the web with Cheerio to extract various information from Twitter

Just starting out with Web Scraping, using Axios to fetch the URL and Cheerio to access the data. Trying to scrape my Twitter account for the number of followers by inspecting the element holding that info, but not getting any results. Attempting to exec ...

What is the best way to implement a calendar view for selecting time periods on an HTML page?

Is there a way to implement a calendar view when clicking on the input box within an HTML page? I am looking to create a function where users can select a time period to generate a file. How can this be accomplished? If possible, could you share some samp ...

The hidden visibility feature only activates when the mouse is in motion

visibility: hidden doesn't take effect until the mouse is moved. const link = document.getElementById("link"); link.onclick = (event) => { link.style.visibility = "hidden"; link.style.pointerEvents = "none"; event ...

Trouble with launching Semantic UI modal

I have implemented a button using Semantic UI and set up a click event to open a modal when clicked, but nothing is happening. When I click on the link, there is no response. I'm unsure what the issue might be. Below is the code for the button: < ...

Using assert.rejects() in Mocha and Node: A Complete Guide

Following the instructions in the documentation, I attempted to use assert.rejects to test for an error message (I have Node version above v10). However, no matter what message I specify, the test always passes. What could be causing this issue? it("is f ...

Tips for transforming a scroll element into the viewport using Angular 2+

This is a sample Here is a component with a list of items: class HomeComponent { text = 'foo'; testObject = {fieldFirst:'foo'}; itemList = [ '1', '2', '3', & ...

Combining React-Redux and Bootstrap: A sophisticated modal feature

Struggling with the distinction between components and containers when using Bootstrap's modal in React-Redux. Instead of repetitively creating modals, I aim to develop a React Component that encompasses a modal template. For clarification, here&apo ...

Trigger a fixed bottom bar animation upon hover

I have a bar fixed to the bottom of the browser that I want to hide by default. When a user hovers over it, I want the bar to be displayed until they move their cursor away. <!doctype html> <html> <head> <meta charset="utf-8"> &l ...

Creating a custom useStorage hook to easily save a Set data type in local storage

I attempted to make modifications to the code found at this reference link: useLocalStorage hook my goal was to enable saving a Set() to localStorage. useLocalStorage.js import { useState, useEffect } from "react"; // Custom Hook export const ...

Tips for maintaining a fixed height for a div while its content is being updated

<div id='wrapT'>some content here</div> <div id='btnsT'> <img id='prev' src='btns/prev_01.png' alt='prev'> <img id='next' src='btns/next_01.png' alt='next ...

How can one decrease the size of a React project?

After running npx create-react-app my-app, the download was quick but then it took over an hour for the installation process to complete. Upon checking the size of the newly installed project, I found that the node_modules folder alone was a whopping 4.24 ...

How to upload a file in ReactJS with the help of jQuery

I am facing a challenge while trying to upload a file to one of my localhost folders using reactjs and jquery. Upon submitting the file, no errors are reported, however, upon checking the folder, I find that it is empty - nothing has been uploaded. upload ...

Mastering Vuex: effectively managing intricate data structures and dynamic state transformations

Let's say I'm utilizing an external API that interacts with Machine objects. With the API, you can create a Machine using createMachine, resulting in a complex object with various nested properties and functions to modify its state. The API inclu ...

Is it possible for a chrome extension to allow only specific third-party cookies and storage to be

My Chrome extension inserts an iframe from foo.com into bar.com, creating a situation where bar.com now includes a foo.com iframe. However, I have observed that this iframe encounters difficulties when attempting to write to localStorage if the user has ...

Exploring ways to display a JavaScript object on click from a .json file

As I delve into the world of javascript and json, I find myself facing a challenge. I am looking to extract information (using the Get Information function) from a json file within a javascript function triggered by an event. The catch is, I want to accom ...

Looking to verify the existence of a div using jQuery once other jQuery functions have executed and created HTML?

Is there a way to verify if a specific element exists within newly added HTML after clicking a button? I attempted this code snippet: $(document).on('click', '#add-html-code', function() { if ($('#something').length ...

Issue: unhandled exception: Marketplace URI is not valid

It seems like I am the first one in this community to ask a question related to balancedpayments. I recently started working with balancedpayments. Here's what I've done so far: Set up a test marketplace Added a "webhoo ...

I am experiencing issues with the loading of CSS and JavaScript files in my recently created Laravel project

Recently, I received a Laravel project and successfully downloaded its configuration to get it up and running using php artisan serve. Upon attempting to access the project through localhost:8000, only the HTML content is displayed without any styling fro ...

Troubleshooting regex validation issues in a JSFiddle form

Link to JSFiddle I encountered an issue with JSFiddle and I am having trouble figuring out the root cause. My aim is to validate an input using a regex pattern for a person's name. $("document").ready(function() { function validateForm() { var ...