What is the best way to separate a string using JQuery?

My menu contains PNG icons. I am looking to achieve a hover effect where the PNG icon changes to a GIF icon when the user hovers over a menu item. I've attempted the following: jsFiddle

$("#image").mouseenter(function(){
    // I can set GIF url here
    $(this).attr("src","http://jsfiddle.net/img/logo.png");
});

$("#image").mouseleave(function(){
    $(this).attr("src","http://jsfiddle.net/img/logo-white.png");
});

However, I understand this isn't the ideal approach as it would need to be done individually for each menu item. This is my HTML structure:

<ul>
    <li>
        <a> item 1
        <img src="image-path" />
        </a>
    </li>
    <li>
        <a> item 2
        <img src="image-path" />
        </a>
    </li>
</ul>

I referred to this question, but it doesn't exactly meet my requirements. I aim to split at the last . or last / in the path.

Currently, the code splits the string at every /:

var data =$("#image").attr("src");
var array = data.split('/');

Question:

The image path I have is: ../images/icon1.png and I want to change it to either of these paths:

../images/icon1.gif or ../images/hover/icon1.gif

Answer №1

Attempt

$('ul img').hover(function (e) {
    $(this).attr('src', function (idx, src) {
        return src.replace(/(.)(png|gif)$/i, '.' + (e.type == 'mouseenter' ? 'gif': 'png'))
    })
})

Example: Fiddle

Answer №2

No JavaScript required for this task.

You can achieve the desired outcome using pure CSS.

.pic{background-image:url(../images/photo.png);}
.pic:hover{background-image:url(../images/photo1.png);}

Answer №3

To remove the final three characters, simply use this code:

let previousUrl = this.src;
this.src = previousUrl.slice(0,previousUrl.length-3) + "jpg";
// or +"jpeg" to switch to a JPEG image.

Answer №4

Did this solution work for you?

$(this).attr('src', 'http://jsfiddle.net/img/logo-white.png');

Answer №5

It's true, JS is not necessary for this task.

Consider the following approach:

.icon {
    width: 32px; /* Customize as needed */
    height: 32px; /* Customize as needed */
}
.icon-house {
    background-image:url(../images/icon-house.png);
}
.icon-house:hover {
    background-image:url(../images/icon-house-hover.png);
}
.icon-car {
    background-image:url(../images/icon-car.png);
}
.icon-car:hover {
    background-image:url(../images/icon-car-hover.png);
}
/* Repeat for other icons... */

Modify your HTML like so:

<ul>
    <li>
        <a href="index.html">Home
        <span class="icon icon-house"></span>
        </a>
    </li>
    <li>
        <a href="carsrock.html">Cars are awesome!
        <span class="icon icon-car"></span>
        </a>
    </li>
</ul>

Alternatively, you could use a spritesheet to improve user experience by reducing image downloads.

For more details, check out this resource: http://css-tricks.com/css-sprites/

Answer №6

Replace the path using a regular expression:

var updatedPath = $(this).attr("src").replace(/\.png$/, ".gif");
$(this).attr("src", updatedPath);

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

Having trouble passing multiple associative array values from JavaScript/AJAX to PHP

We have been encountering an issue when trying to pass multiple associative array values from JavaScript/AJAX to PHP, as the PHP file is receiving an empty object/array. Could someone kindly assist us in retrieving the values of an associative array from ...

capturing elements while showcasing others through CSS

I am facing a dilemma with my classes for the menu and content sections of my website. The menu is controlled by .site-header-menu class. Meanwhile, the content section is managed by the .content class. I want to know how I can target the .content when th ...

Exploring the concept of upserting records using the MongoDB $

I am working with two collections in my database: Regions and Registrations. var RegionSchema = new Mongoose.Schema({ name: {type: String}, registrations: [{type: Mongoose.Schema.Types.ObjectId, ref: 'registrations'}], ... }); The Registr ...

The POST Method encountering issues within the <code> tag

<form name="submit_form" action="./uploads/submit.inc.php" method="POST"> <div class="wrapper"> <code id="ace-editorid" name="code_editor">Input Your Code Here</code> </div> <script sr ...

Tips for seamlessly incorporating React Epub Reader into your next js project

Having some trouble integrating the react epub reader with Next Js. It's working perfectly fine with react js, but I keep encountering an error. Can you help me figure out how to integrate the epub reader with next js? Here is the error This is my ...

Having issues with the Vuetify component, specifically the v-date-picker not functioning properly

Hey there! I'm still getting the hang of vuetify and have been experimenting with creating functions using simple components. One such component I've been using is v-date-picker. However, I've encountered an issue where the calendar doesn&a ...

The Three.js effect is functional on Firefox but experiencing issues on Chrome

I have recently implemented a recursive search for adjacent faces using a Half Edge data structure and I am facing an issue where the effect is visible on Firefox but not on Chrome. I am seeking assistance in resolving this problem. Any help or suggestions ...

What is the best way to combine the elements within an array with the elements outside of the array in order to calculate their sum?

The goal is to create a function that determines the winner using two input integers. The function should return the first input if it is greater than the second input. function determineWinner(a, b) { let result = [] for (let i = 0; i < 3; i++) ...

Keep an ear out for socket.io within an Angular application

I am trying to connect socket.io with my angular application. I have come across some examples of creating a service that can be accessed by the controller, and I understand that part. However, I am looking for a solution where all controllers can respond ...

Unable to retrieve content in NGX-Quill upon submission

I am currently using "ngx-quill": "^14.3.0" along with "@angular/core": "~12.2.0". It is registered in the app module: QuillModule (not for root). And also in the lazy loaded module: QuillModule (not for root). public editor = { toolbar: [ ...

Attempting to download an image through an axios fetch call

There is an issue I am facing while trying to retrieve an image from the website www.thispersondoesnotexit.com. function getImage() { axios({ method: 'get', url: 'https://www.thispersondoesnotexist.com/image' }) ...

The previous background image that was functioning properly is no longer showing up after upgrading to Laravel 6.0

I'm struggling with getting a background image to show in my view that contains a <body></body> tag. I was able to do it before, but now it's not working. The background image is downloaded on my computer and stored in the public fold ...

Contrast between the functionalities of $.ajax and $.post

$.post( url, data, callback, type ); $.ajax () Is there a distinction between using $.post and $.ajax in jQuery? And if so, which method is recommended? Also, how many parameters can be passed to the $.ajax function? ...

Using Jquery to swap out elements with a specific delimiter

How can I dynamically modify a string like the one shown below? var str = "<div class=\"@@obj.classname@@\" style="\@@obj.color@@\">@@obj.content@@</div>"; I want to create a function that will transform it into the follow ...

Adjust the color when hovering with the mouse

I want the border color to change to black instead of #FF00FF when hovering over an image. Here's my current JavaScript code: javascript:for(i=0;i<document.getElementsByTagName('img').length;i++) { var imgTag=document.getElem ...

"Issue with Material-ui Autocomplete where the defaultValue does not function properly

The defaultValue was set to "Chairs" but it doesn't seem to be working as expected. Here is the code snippet: import React, { useState } from "react"; import TextField from "@mui/material/TextField"; import Autocomplete from "@mui/material/Autocomple ...

Understanding Express.js API Function Parameters

The API documentation for Express mentions that the format for a function is "app.use([path,] function [, function...])". However, in the app.js file generated by the Express generator, there is a line of code like this: "app.use('/', routes);", ...

ng-class in AngularJs updates the class of all items within ng-repeat in the view

When applying AngularJs' ng-class, I encounter an issue where the class gets updated and applied to all items in the ng-repeat directive instead of just the specific item that was clicked. Even when using data-target="#collapse_{{ $index }}", it does ...

Identify a consistent pattern across various strings using Python

I'm dealing with a few file names : xyz-1.23.35.10.2.rpm xyz-linux-version-90.12.13.689.tar.gz xyz-xyz-xyz-13.23.789.0-xyz-xyz.rpm In these file names, 'xyz' can be any string of any size (only alphabetic, no numerals) The numbers separ ...

Center the background image and adjust it vertically up or down as needed

I am experiencing an issue with a slider div that has a background image on it. The background image is too large, so it is currently centered. You can see the issue here: http://jsfiddle.net/s5qvY/ <div id="slider"></div><hr><hr>& ...