Update the image source when hovering over the parent element

Check out this snippet of HTML code:

<div class="custom text-center threeBox ofsted">
  <a class="ofsted" title="ofsted report" href="http://reports.ofsted.gov.uk/">
    <img class="text-center ofstedLogo" src="images/ofsted_good_transparent.png" alt="ofsted good rating">
    <h3>Ofsted</h3>
    </a>
</div>

I came up with some jQuery code that changes background colors when hovering over a link:

    $(".threeBox a").hover(
        function(){ // Mouse Over
            $(this).parent().addClass("swapBg");
        },
        function(){ // Mouse Out
            $(this).parent().removeClass("swapBg");
        }
    );

It's all good, but now I want to replace the image src with 'OFSTED_good_logo.jpg' when hovering over the link. I've tried tweaking the jQuery code, but it's not working. Can anyone help with this problem please?

Answer №1

If you want to change the image source using find() and attr(), you can do so by utilizing the following jQuery script:

$(".threeBox a").hover(
        function(){ // Hover Over
            $(this).parent().addClass("swapBg").find('img').attr('src','new_image.jpg');
        },
        function(){ // Hover Out
            $(this).parent().removeClass("swapBg").find('img').attr('src','default_image.png');
        }
    );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="custom text-center threeBox ofsted">
  <a class="ofsted" title="ofsted report" href="http://reports.ofsted.gov.uk/">
    <img class="text-center ofstedLogo" src="images/default_image.png" alt="ofsted good rating">
    <h3>Ofsted</h3>
    </a>
</div>

Answer №2

Learn how to utilize the attr() method effectively

$(".threeBox a").hover(
        function(){ // When the mouse is over
            $(this).parent().addClass("swapBg");
            $(this).find('img').attr('src', 'images/OFSTED_good_logo.jpg');
        },
        function(){ // When the mouse is out
            $(this).parent().removeClass("swapBg");
            $(this).find('img').attr('src', 'images/ofsted_good_transparent.png');
        }
    );

Answer №3

Here is a simple solution to achieve the desired outcome:

$(this).find('.myLogo').attr('src', 'yournewimage.png');

For more information, check out attr documentation

Answer №4

To manipulate the image, utilize the .find() method to select it and the .attr() method to modify the src attribute:

$(".threeBox a").hover(
    function(){ // Triggered when mouse is over
        $(this).parent().addClass("swapBg");
        $(this).find('img.ofstedLogo').attr("src", "images/OFSTED_good_logo.jpg");
    },
    function(){ // Triggered when mouse is out
        $(this).parent().removeClass("swapBg");
        $(this).find('img.ofstedLogo').attr("src","images/ofsted_good_transparent.png");
    }
);

Answer №5

There are several ways to achieve this particular effect using a graphical approach. Take a look at the example provided in the JSFiddle link below:

Utilizing jQuery for direct image replacement:

$(".twoBox > a").hover(
    function(){ // Mouse Over
        $(this).find('img:first').attr("src", 'http://blog.modernica.net/wp-content/uploads/2011/12/2-300x300.png');
    },
    function(){ // Mouse Out
        $(this).find('img:first').attr("src", 'http://www.adamcentric.com/wp-content/uploads/2014/09/1-300x300.png');
    }
);

OR utilizing jQuery for CSS class swapping:

.ofstedLogo2 {
    height: 300px;
    width:300px;
    background-image:url(http://www.adamcentric.com/wp-content/uploads/2014/09/1-300x300.png); 
}
.ofstedLogo3 {
    height: 300px;
    width:300px;

background-image:url(http://blog.modernica.net/wp-content/uploads/2011/12/2-300x300.png); 
}
$(".threeBox > a").hover(
    function(){ // Mouse Over
        $(this).find('div:first').toggleClass("ofstedLogo2");
        $(this).find('div:first').toggleClass("ofstedLogo3");
    },
    function(){ // Mouse Out
        $(this).find('div:first').toggleClass("ofstedLogo2");
        $(this).find('div:first').toggleClass("ofstedLogo3");
    }
);

Link to the JSFiddle example

One method involves directly replacing the IMG source, while the other method involves swapping CSS background images.

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

Creating dynamic visual elements on a webpage using HTML: Video

As I continue to learn HTML, CSS, and JavaScript to create a basic website for educational purposes, I have successfully embedded a video stored in my drive using the video element on an HTML page. However, I now aim to also display the video's title, ...

Using jQuery to upload a file and check for empty input fields

CSS <input type="checkbox" style="visibility: hidden" id="checkme" /> <br /> <input type="button" id="clickhere" value="Check It Out!" /> JavaScript $(function(){ $('#clickhere').click(function(){ $('#checkm ...

Is it possible for a bootstrap carousel to rotate carousel items belonging to two separate carousel identifiers?

My Bootstrap 4 carousel setup is as follows: <div class="col-12"> <a class="carousel-control-prev text-dark" href="#myCarousel" role="button" data-slide="prev"> <span class=" ...

Exploring scroll functionality with Webdriver.io v4

My code is designed to log into the beta version of mediawiki, navigate to the Preferences page, and attempt to click on a button located at the bottom of the page. In order to achieve this, I am utilizing the scroll() function because using only .click() ...

Setting up RTL (Right to Left) functionality in Material UI version 5 - A Step-by-Step Guide

After updating my app to version 5 of Material-UI from version 4, I noticed that the RTL support is no longer functioning. I carefully followed the instructions in the documentation: https://mui.com/guides/right-to-left/ The current outcome is that the ...

What is preventing the listener from activating?

I came across some HTML code that looks like this: <form id="robokassa" action="//test.robokassa.ru/Index.aspx" method="post"> <input type="text" id="OutSum" name="OutSum" value="" placeholder="Сумма пополнения"> ...

Using the Strikethrough Feature in React

Is it possible to apply a strikethrough effect to a checkbox's label text when toggled on and off? In my system development process, I've utilized various methods. What modifications should be made in the fComplete method for this feature to wor ...

Why does my contact form display PHP code unexpectedly?

I've been following a YouTube tutorial to create a responsive single-page website using Bootstrap. The tutorial covered the front-end, but now I'm stuck on integrating a contact form. I added some PHP code I found online, but there seems to be an ...

Does the onwheel event get triggered when scrolling on a trackpad?

Despite being a fundamental inquiry, the answer remains elusive to me. Due to its simplistic nature, there isn't much of an elaborate explanation available. Regrettably, I am lacking access to a laptop for testing purposes. ele.onwheel = function(e) ...

Switch out multiline text with javascript

Could someone assist me with this question? I am attempting to locate and replace specific code within a JavaScript file. The code is included in an AJAX response that contains a significant amount of HTML code. After retrieving the AJAX response, I stor ...

Is there a delay following the click on the file upload button?

Whenever I attempt to choose a file for upload by clicking on "Select File" (input type=file), there seems to be a lag between the moment I click the button and when the selected file appears next to the button. It almost seems as if the browser is attempt ...

Using Google App Script's pageToken to store attachments on Google Drive

Essentially, my goal is to save all attachments from received emails to a specific folder in Google Drive (mostly .PDF files). However, I've encountered a limitation with the search function which only allows me to retrieve up to 500 attached files. I ...

ways to dynamically retrieve input values in PHP

Is there a way to dynamically add and remove data fields, as well as increase and decrease fields dynamically in PHP? I am looking to retrieve the subject value in an array or JSON format using PHP only. https://i.stack.imgur.com/HqDCz.png <div data-ro ...

Angular Universal causing issues with updating the DOM component

@Component({ selector: 'mh-feature-popup', template: ` <div class="full"> <div> <div class="container-fluid" [@featurepop]="state"> <div class="row"> <div class="col-xs-12 col-md-4 col-md-offse ...

Despite encountering Error 404 with AJAX XHR, the request is successfully reaching the Spring Controller

I am attempting to upload a file with a progress bar feature. var fileInput = document.getElementById('jquery-ajax-single') var form = new FormData(); form.append('uploadFile',fileInput.files[0]); $.ajax({ url: "fi ...

The setTimeout function fails to behave as intended when used in conjunction with synchronous ajax

Within my code, I have a function that is being invoked multiple times due to iterating through an array of length n and creating 'Plants' with synchronous ajax calls. These calls involve querying the Google Maps API, so it is crucial to throttle ...

LESS: Using variable values in mixin and variable names

I am looking to simplify the process of generating icons from svg-files while also creating a png-sprite fallback for IE8 support. I am using grunt.js and less. I was inspired by the implementation on 2gis.ru: (in Russian), where they used technologies s ...

What is the best way to trigger a child function from the parent component in React?

In my React application, there are three components: two child components and one parent component. I need to pass data (projectId) from ChildOne to ChildTwo through the Parent component and trigger a function once the data is received. Essentially, I am s ...

Vue.js blocks the use of iframes

I've come across a peculiar issue where I need to embed an iframe inside a Vue template and then be able to modify that iframe later. The code snippet below shows the simplified version of the problem: <html> <body> <div id="app" ...

Mapping an object in ReactJS: The ultimate guide

When I fetch user information from an API, the data (object) that I receive looks something like this: { "id":"1111", "name":"abcd", "xyz":[ { "a":"a", "b":"b", "c":"c" ...