JavaScript: Replace image title on mouse over

I am having trouble adding '_hover.jpg' to my images on mouse over. Can anyone provide assistance with this issue? Thank you in advance.

<script type="text/javascript>
$(document).ready(function () {


$(".img").mouseover(function (e) {    
$(this).attr("src", $(this).attr("src").replace(".jpg", "_hover.jpg"));
}).mouseout(function (e) {
$(this).attr("src", $(this).attr("src").replace("._hover.jpg", ".jpg"));
});

)} 

<li class="hex">
<div class="hexIn">
<img src="/images/leaderboard.jpg" alt="" class="hex-img"/>
  <h2>Joe Bloggs<br>from ACME<br>volunteered at<br>Inspire<br>on 3 July</h2>
</div></li>

Many thanks

Answer №1

$(".hex-img").mouseover(function () {    
$(this).attr("src", $(this).attr("src").replace(".jpg", "_hover.jpg"));
$(".test").text($(this).attr("src"));
}).mouseout(function () {
$(this).attr("src", $(this).attr("src").replace("_hover.jpg", ".jpg"));
$(".test").text($(this).attr("src"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="test">Hello</p>
<li class="hex">
<div class="hexIn">
<img src="abc.jpg" class="hex-img" width="100px" height="100px"/>
  <h2>Joe Bloggs<br>from ACME<br>volunteered at<br>Inspire<br>on 3 July</h2>
</div></li>

Answer №2

It appears that the selector used was incorrect; it should be img instead of .img, as you are targeting a class name. The correct class name to use is hex-img. Additionally, the function document.ready was not properly closed. It should be closed with } instead of )}

$(document).ready(function() {
      $("img").mouseover(function(e) {
        $(this).attr("src", $(this).attr("src").replace(".jpg", "_hover.jpg"));
        console.log($(this).attr("src"))
      }).mouseout(function(e) {
        $(this).attr("src", $(this).attr("src").replace("._hover.jpg", ".jpg"));
        console.log($(this).attr("src"))
      });
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="hex">
  <div class="hexIn">
    <img src="/images/leaderboard.jpg" alt="" class="hex-img" />
    <h2>Joe Bloggs<br>from ACME<br>volunteered at<br>Inspire<br>on 3 July</h2>
  </div>
</li>

Answer №3

<style>
.hex-img:hover {
background-image: url('_hover.jpg');
}

.hex-img {
background-image: url('original.jpg');
}
</style>

Answer №4

Using default HTML tags without adding the . or # is commonly done, but it is not considered a professional practice. It's best to always select elements based on their unique id or class. Please update this line of code accordingly.

$("#image").click(function (event) { 

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

Passing an array from PHP to the DataTables JavaScript library

I am attempting to pass a PHP array to the JS Datatable library for testing purposes. Instead of fetching data from a database, I have simplified my approach. Here is a basic representation of my PHP code: $data_fmt['data'][] = array("TEST"); e ...

Using Ajax and PHP to store multiple checkbox selections into the database

I currently have 32 checkboxes on my page that I need to track the checked status for. In my JavaScript, I am looping through each checkbox and assigning a value of '1' for checked and '0' for unchecked. // Example for one checkbox if ...

Tips on merging HTML node lists from various `getElement`s

Is there a way to combine HTML elements and extract values using array methods? I am struggling to merge them as a nodeList. I tried using get elements and array.unshift to consolidate elements into one variable. var elemsLabel = document.querySelecto ...

Incorporating Multiple Slots for Content Transclusion in Angular 6

In my quest to implement a component with multi-slot transclusion in Angular 6, I came across a valuable resource on this blog post (originally written for Angular 2). The initial step involved creating a component: import { Component, OnInit } from &apos ...

Apply a class when a form field is deemed invalid

I am working on using jQuery validation for ajax form submission, and I am facing an issue where I would like to add a class to the errorContainer if any of the text inputs have a class 'error'. It seems simple, but I believe it may be a scope is ...

Showcase information from APIs using Vue.js

I am facing an issue where I am able to fetch data correctly from the API, but I am unable to display it. When I manually input items, they are displayed, but the items fetched from the API remain invisible. I even attempted to move the API call directly i ...

Transforming arrays with map or alternative methods in javascript

Below is the JSON object I am working with: { id: 3, cno: 103, username: 'basha', name: 'New Complaint', desc: 'Need bag', storeId: [ 5, 1 ] } My desired output should look like this: [ {id: 3,cno: 103, ...

Encountering a "Karma error: resource not discovered" while examining an AngularJS application

I'm attempting to run my AngularJS application in Netbeans IDE, and I believe I've set up the files correctly. However, an error is appearing when I try to test it by right-clicking on my project and selecting Test: Karma cannot start (incorrect ...

Changing Background Images Based on Screen Size in CSS Media Queries

Hey there, I am currently using two different header images - one for desktop and another for both tablet and mobile devices. I am wondering how I can automatically switch from the desktop header image to the mobile/tablet header image when the screen siz ...

Selenium Webdriver experiencing issues with running JavaScript code

Looking to extract data from an Aliexpress product page? Take a look at this example. Specifically, I am interested in this section (transaction history). Here is my code snippet: from selenium.webdriver.chrome.options import Options from selenium impor ...

Jquery code fails to execute unless a breakpoint is set

I'm encountering a strange issue with the jquery star rating plugin. It seems that only when there's a breakpoint in my JS code will the radio buttons transform into stars; otherwise, they remain unchanged. Let me break down the code step by step ...

Tips for expanding css modules within next js

I am new to working with Next.js and I have a query regarding CSS modules I currently have a Product component structured as follows: import styles from "./Product.module.css" function Product({className=""}) { return ( <div ...

Ways to modify the end result using callback information

In my scenario, I am working with an object that has keys id and name as shown below. The goal is to retrieve the customer name based on the id and then update the object accordingly. Const arr=[{id:1,name:''},{id:2,name:''}]; ...

AngularJS promise fails to resolve when attempting to read a file using the FileReader

Can someone assist me with a function I am trying to create in my service? I want the function to use FileReader to read a small image file and return the result in a promise to my controller. The issue is that while the file reaches the service without an ...

Ways to automatically divide lists into various div elements

Hey there! I currently have a list of categories on my page that is subject to change. I'm looking for assistance in creating a loop that will divide my lists into groups of 5 items per div. For example: foreach($categories as $cat) <label> ...

position the next and previous buttons of the bootstrap carousel to be located outside of the images

I am currently using a bootstrap carousel with the following code: <div class="slider-main-container d-block"> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> ...

Leveraging Next.js to efficiently handle multiple asynchronous requests with NextResponse

I have developed a login/signup application using NextJS. When attempting to log in, the logic in my route.ts file sends requests to a MongoDB database to check if the user exists and if the password is correct. However, instead of receiving the expected 4 ...

Throttling of Node server due to frequent AJAX requests (using Express and jQuery)

As a beginner in the world of Node.js, I am exploring its functionalities and experimenting with some basic tasks to better understand how it operates. Currently, I have set up a client webpage that includes a button triggering a simple AJAX GET request u ...

Transferring information between AngularJS and Express/Node without using AJAX

My application is built using AngularJS on a node/express backend, with user authentication handled by passport. After a user signs in or signs up, the communication between my Angular controllers and express is done through $http ajax/xhr calls. The form ...

JavaScript error message stating that the setAttribute function is null

As a newcomer to JS, I am currently working on creating a task list webpage that allows users to submit projects and create task lists within each project with designated due dates. In order to generate unique ID tags for projects and tasks, I utilized UU ...