Switching images through onmouseover, onmouseout, and onclick interactions

I have two images named img1 and img2. Here is my code:

function roll(id, img_name, event_name, img_id)
 {
    var state ;
    if(event_name == 'mouseover')
    { state = false;rollover();}
    else if(event_name == 'mouseout')
    {state = false;rollout();}
    else if(event_name == 'onClick')
    {alert(event_name);state = true;showdata(id,img_name,state);}
    else
    {showDIV(id);}
    
   function rollover()
   {
        if(state == false)
        {
            var imgpath='image_file/'; 
            document[img_name].src =imgpath + img_name + '_over.png';
        }
   }
   function rollout()
   {
        if(state == false)
        {
            var imgpath='image_file/'; 
            document[img_name].src = imgpath + img_name + '.png';
        }
   }
    function showDIV(id)
    {  
        var div = document.getElementById(id);
    if ( div.style.display != "none" ) 
    {
    div.style.display = "none";
    document[img_name].src='downarrow.png';
    
    }
    else 
    {
    div.style.display = "block";
    document[img_name].src='uparrow.png';
    }
    }
    function showdata(id,img_name,state,img_id)
    {alert(state);
        if(state == true)
        {
            var imgpath='image_file/'+ img_name;
            var div = document.getElementById(id);
        if ( div.style.display != "none" ) 
        { alert('none' +state);
            document.getElementsByName(img_name).src =imgpath + '.png';
        div.style.display = "none";
        }
        else 
        {   alert('block :' +state);
            document.images[img_name].src='image_file/journey_icon_over.png';
        div.style.display = "block";
        }
    }
    }
}
    <tr>
    <td valign="top" width="100%">
    <img id="img1"  name="journey_icon" src="image_file/journey_icon.png"  alt="Journey Report" onmouseover="roll('JourneyReport','journey_icon','mouseover')" onmouseout="roll('JourneyReport','journey_icon','mouseout')" onclick="roll('JourneyReport','journey_icon','onClick',this.id)" />
    <div id="JourneyReport" style="display:none;" class="divbackground">
    <uc1:ReportControl ID="JourneyControl" runat="server" />
    </div>
    </td>
    </tr>

The requirement is that I need img1 to change on mouseover and img2 on mouseout. This functionality is working fine, but on Click, I need the div to be opened and img2 to freeze while allowing mouseover and mouseout states to work again. The current issue is that on click, the div appears but the mouseover and mouseout functions are also triggered.

Khushi

Answer №1

To prevent the events from bubbling up, make sure to include the following line at the end of your onclick code:

window.events.cancelBubble = true;
. Test it out to see if this solution works for you. Keep in mind that this may not necessarily stop the mouseover and mouseout events, but give it a try nonetheless.

Answer №2

Hey, I successfully organized an event using logical thinking... The conditions I used were quite unique.

When hovering over the element, a function is called to display the First Image.

When moving the mouse away from the element, a function is triggered to display the image that should appear after clicking.

Upon clicking on the element, the last clicked image is saved in a hidden field. Additionally, a function is called to display the desired image after the click (referred to as "snd function"), and return false;

That's all! Instead of passing the image URL as a parameter onmouseout event, create a Javascript function to retrieve the URL within the "Save last clicked image" function (the first function used on onclick event).

I believe this explanation will be beneficial to you.

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

Achieving the highest ranking for Kendo chart series item labels

Currently, I am working with a Kendo column chart that has multiple series per category. My goal is to position Kendo chart series item labels on top regardless of their value. By default, these labels are placed at the end of each chart item, appearing o ...

What is the best way to add a dynamic parameter to the URL?

Here is an example of my URL: https://my-website.com/api/players?countryId=1&clubId=2&playerName=abc The parameter values can vary. This is the code snippet I use: getDataPlayer(payload) { let params if(payload.countryId && payl ...

Using Ajax to fetch project data from an API

Currently immersed in a personal coding project, I'm struggling to troubleshoot my code. Essentially, I need to retrieve data from an API and display it on my HTML page. The data type is "jsonp" due to CORS errors that required this workaround for de ...

Are Global variables supported in the EXT JS framework?

When working with Java and C++, it is common practice to store a variable globally so that its value can be accessed from anywhere within the project. For example, if I am working inside a class named Residence and saving an INT as the residenceNumber to a ...

The useEffect hook fails to recognize changes in dependencies when using an object type obtained from useContext

Utilizing the useContext hook to handle theme management in my project. This is how the ThemeContext.js file appears: "use client"; import { createContext, useState } from "react"; let themes = { 1: { // Dark Theme Values ...

Retrieving an array using the $.post() method

I am utilizing the following code: $.post('fromDB.php', function(data) { eval(data); console.log(data); updateTimer(); }); In order to retrieve arrays from PHP. This is what PHP returns: var todayTimeMinutes = [0, 45, 35, 25, 40, 0 ...

Tips for retaining the selected radio button in a Java web application even after a page refresh

As someone new to web development using the Stripes Framework, I am encountering an issue with radio buttons on a webpage. When one of the radio buttons is selected, a text box and Submit Button appear. After clicking the Submit button, the functionality ...

Elevate your website design by adding interactive Ripple Buttons using a combination of Javascript and

Recently, I came across a script that allows for an animation to occur when a button is clicked. However, I have encountered an issue where the script does not redirect to a link. (function() { var cleanUp, debounce, i, len, ripple, rippleContainer, rip ...

Accessing process.env in Nest.js controllers

Is there a way for me to access process.env.SOME_FIELD in nest.js? app.module.ts ... modules: [ ... ConfigModule.forRoot({ envFilePath: '.env.' + process.env.APP_CODE }), CatModule ... ] ... CatController.ts ...

Cycle through the list and populate the table with the data

My attempt to clarify this explanation is my best, as articulating exactly what I am trying to achieve is quite challenging: Initially, I have a list of names: { "Items": [ { "Id": 0, "Name": "Robinson" }, ...

Calculating a Price Quote

I have created a dynamic quote calculator for a Next.js project that allows users to calculate prices based on word count and selected languages. Currently, the price is calculated using a fixed rate of 0.05 per word. 'use client'; import { useS ...

Choose a particular optgroup simultaneously using custom JavaScript

Check out this Fiddle for an example I am facing a situation where I have two different types of option groups with options. My challenge is to ensure validation between these two groups. How can I achieve this? Situation 1 If I select something from g ...

What is the best way to modify or revise meta fields for individual products in order to retrieve multiple images for each product in Shopify?

What is the process for updating or editing meta fields to display multiple images of each product on Shopify? ...

What is the best way to send a JavaScript variable to Django using AJAX?

I am facing an issue while trying to pass an array in json format using ajax to my django views. Even though I receive a status of 200 indicating that the POST request has been successfully made, when I attempt to display the data passed in another templat ...

A guide on sorting an array based on elements from a different array

We are currently in the process of developing an application using Vue and Vuex. Our goal is to display a list of titles for venues that a user is following, based on an array of venue IDs. For instance: venues: [ {venue:1, title: Shoreline} {venue:2, ti ...

Node.js command prompt claims that 'react is non-existent'

Hello everyone! I'm excited to ask my first question on this site. I am relatively new to coding and currently learning React. Yesterday, I started working on my first project. Today, when I tried to initialize live-server and babel compiler for my J ...

Unable to display search results with AJAX in Select2

I'm struggling with getting the desired outcomes to display in Select2 when using AJAX. Below is my code: $(document).ready(function() { $("#producto").select2({ placeholder: 'Select a product', formatResult: productForm ...

Is it possible for me to send transactions asynchronously using polkadot-js?

After thoroughly going through the official documentation, I stumbled upon a page discussing how to transfer using polkadot-js const transfer = api.tx.balances.transfer(BOB, 12345); const hash = await transfer.signAndSend(alice); I am curious if it' ...

Animate the CSS when the content is within the viewport using pagepiling.js integration

I'm currently working on animating content as it enters the viewport. However, I've encountered an issue where jQuery (used to check if the content is in the viewport) isn't functioning properly alongside pagepiling.js (). I suspect this mig ...

Employing asynchronous operations and the power of async/await for achieving seamless integration

I am currently facing an issue where I need to retrieve queries from a database stored in Postgres. A function is utilized, which employs a callback mechanism. In order to fetch rows from the database, there exists a function called getRecipesByCategoryFo ...