Changing pictures using jQuery tabbing

After modifying a jQuery tabs script to use images instead of tabs and adding code for image change on hover and click, I'm facing an issue. Whenever I click on an image, the tab should remain active and the image should stay changed, but it keeps reverting back to the original.

Here's my code:

function resetTabs(){
$("#container > div").hide(); 
        $("#tabs a").attr("id","");     
    }
    var myUrl = window.location.href;
    var myUrlTab = myUrl.substring(myUrl.indexOf("#"));      
    var myUrlTabName = myUrlTab.substring(0,4); 

    (function(){
        $("#container > div").hide(); 
        $("#tabs li:first a").attr("id","current"); 
        $("#container > div:first").fadeIn(); 
        $("#tabs a").on("click",function(e) {
            e.preventDefault();
                if ($(this).attr("id") == "current"){
             return       
            }
            else{             
            resetTabs();
            $(this).attr("id","current"); 
            $($(this).attr('name')).fadeIn(); 
            }
        });

        for (i = 1; i <= $("#tabs li").length; i++) {
      if (myUrlTab == myUrlTabName + i) {
          resetTabs();
          $("a[name='"+myUrlTab+"']").attr("id","current"); 
          $(myUrlTab).fadeIn(); //      
      }
    }
})()  

$(function(){
$('.hoverfun').on('mouseenter mouseout', function(){
  var original = $(this).attr('src');
  var replacement = $(this).data('hoverimg');       
  $(this).attr('src', replacement).data('hoverimg', original);
    });
});

$(function(){
$('.hoverfun').on('click', function(){
  var original = $(this).attr('src');
  var replacement = $(this).data('downimg');
  $(this).attr('src', replacement).data('downimg', original);
    });
});

<ul id="tabs">
  <li><a href="#" name="#tab1"><img class="hoverfun" src="images/img1.png" data-hoverimg="images/img2.png" data-downimg="images/img3.png"></a></li>
  <li><a href="#" name="#tab2"><img class="hoverfun" src="images/img1.png" data-hoverimg="images/img2.png" data-downimg="images/img3.png"></a></li>
  <li><a href="#" name="#tab3"><img class="hoverfun" src="images/img1.png" data-hoverimg="images/img2.png" data-downimg="images/img3.png"></a></li>
  <li><a href="#" name="#tab4"><img class="hoverfun" src="images/img1.png" data-hoverimg="images/img2.png" data-downimg="images/img3.png"></a></li>

I understand that it might be a bit messy, but any assistance in debugging this would be greatly appreciated :)

Answer №1

Seeking clarity on your objective, here is a suggestion that might be beneficial.

To enhance functionality, consider assigning a new class like active to .hoverfun upon clicking it.

Subsequently, utilize .hasClass() to verify if the element possesses the class active and prevent mouseover effects accordingly.

$(function () {
    $('.hoverfun').on('mouseenter mouseout', function () {
        if (!$(this).hasClass('active')) {
            var original = $(this).attr('src');
            var replacement = $(this).data('hoverimg');
            $(this).attr('src', replacement).data('hoverimg', original);
        }
    });

    $('.hoverfun').on('click', function () {
        $('.active').each(function() {
            var o1 = $(this).attr('src');
            var o2 = $(this).data('hoverimg');
            var o3 = $(this).data('downimg');

            $(this).attr('src', o2).data('downimg', o1).data('hoverimg', o3).removeClass('active');
        });

        var original = $(this).attr('src');
        var replacement = $(this).data('downimg');
        $(this).attr('src', replacement).data('downimg', original).addClass('active');
    });
});

http://jsfiddle.net/3hqgh/1/

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 come my game is not registering a failure when I click on the same card twice?

UI image of the game. Cards with instruments that are clickableThe objective of the game is to avoid clicking the same card twice. If you do, you lose the game. The issue lies in the fact that it continues to cycle through the cards without ending when the ...

What is the best method to ensure that my background image is fully visible on a webpage?

I'm attempting to place a background image at the center of my webpage, but unfortunately, the image extends beyond the page boundaries and is only partially visible. Below is my CSS code snippet: body{ background-image: url(../img/music_palace_ ...

User currently signed in: What specific information should be transmitted to the web browser?

Experience: Currently utilizing the MEAN stack for a web application and still in the learning process. The Concern: I am facing some confusion regarding a particular aspect. For instance, if a user is logged in (using Passport.js), I can access their inf ...

Set $scope.model childs to an empty string or a null value

While working on a form, I am using a $http request to send the information through Angular in the following manner: $http({ method:"POST", url: "controllers/servicerequest.php", data: { servicerequest: $scope. ...

Revamp your arrays with input fields in Vue3

When presented with two arrays of options, users must select an option from each array. ==> first array: [ orange, green, yellow ] ==> second array: [ orange, green, yellow ] The challenge is to update the second array based on the user's sele ...

Firestore - Issue with updating object accurately

Describing a data structure that I am working with: { assignments: [] faqs_url: "oi" id: "pW68CiGZJMZJzyY1GExz" name: "oi" notes: { file: { extension: "pdf", type: "base64" } name: "o" url: "http://192.168.1.111:3000 ...

Utilizing Moment.js: Transforming 12-hour format to a Date object

Is there a way to convert a 12-hour string into a 24-hour Date object? day.from = day.from || moment("6:00", ["h:mm"]).format("HH:mm"); Unfortunately, I am encountering the following error: angular.js:11706 Error: [ngModel:datefmt] Expected `6:00` to be ...

Using Node JS to query data from MySQL and filter a column based on an array of objects

I am dealing with a column in my database that can either be null, contain a single integer, or multiple integers separated by commas. I need to filter specific rows based on this column. However, instead of using a search string, I have an array that coul ...

Expanding images to fit the div's width in Bootstrap

I've encountered an issue with my grid of resized images - the original images are larger than what can be accommodated by the Bootstrap grid setup. The problem arises when I decrease the width of my window - instead of maintaining the resized size a ...

javascript - Modify the text color of the final word entered

I am currently working on a text editor project and one of the requirements is to change the font color of the last word typed based on whether it is a keyword or not. Despite trying various solutions, I have yet to find one that works as intended. Here is ...

How can I retrieve an array of collections from multiple parent documents in Firebase and pass them as props in Next.js?

I need to access all the collections within the documents stored in a collection named users. This is how I currently retrieve all the user information: export async function getServerSideProps() { const snapshot = await firebase .firestore() .collection ...

Running into an issue with AngularJS' ng-switch where it fails to execute properly unless it is enclosed within a div tag, resulting in the error message: "

Two directives are at play here: app.directive('uiElement', function () { return { restrict: 'A', replace: true, scope: {element: "=uiElement", search: "=search"}, templateUrl: "/views/uiElement.html", link: funct ...

Align two child elements vertically in the center using flexbox

I require your assistance; I have been attempting to center the text vertically within this div, but all my efforts thus far have been unsuccessful. I have included the default layout for reference. While using padding may offer a solution, I believe that ...

The Selenium driver's execute_script() function is not functioning as expected

When I attempt to execute a JavaScript using driver.execute_script, nothing happens and the system just moves on to the next line of Python code. Any ideas? I've been web scraping on a webpage, using JavaScript in the Console to extract data. The Jav ...

The Bootstrap datetimepicker is malfunctioning, displaying an error in the console stating that '$' is not defined

I'm currently using the bootstrap datetimepicker but it doesn't seem to be working correctly. Can someone please point out what I might be doing wrong? Here are the links that I have provided: <script src="{{ asset ('css/sidebar/p ...

Setting the initial values of state variables upon rendering of a component and using custom hooks

I have a file called Body.jsx that handles fetching data from an API and filtering it. In an attempt to clean up the code, I created a custom hook named useResData specifically for fetching data: export const Body = () => { const resDataList = useResD ...

The code functions properly when tested on a local server, but doesn't produce any results when

Currently, I am working on customizing a premade website and have been tasked with making a modification. The goal is to implement a confirmation box that appears when a button to delete a meeting task is clicked, rather than immediately deleting it. Afte ...

Issue with Thymeleaf form not able to retrieve JSON object

Having trouble retrieving JSON objects instead of strings on my HTML page. Any suggestions? Below is the snippet of HTML code causing the issue: <form th:object="${case}" novalidate="true" data-model="case" action="/hcp/patient/details/insurance" meth ...

Change the color of a cell in a mat-table

My mat-table has a basic column structure like this: <mat-table #table [dataSource]="dataSource" matSort> <ng-container matColumnDef="zone"> <mat-header-cell *matHeaderCellDef mat-sort-header></mat-header-cell> ...

Guidelines for incorporating JS in Framework7

I am developing an application using the framework7. I am facing a challenge where I need to execute some javascript in my page-content, but it is not running as expected. <div class="pages"> <div class="page close-panel" data-page="item"> ...