How to swap button image upon click in HTML

Is it possible to change the image of a button when it is clicked?

   #button {
    text-align:center;
    float:left;

    }

   #button:focus {
    text-align:center;
    float:left;
    background-image: url('qmb2.png');

    }


   <input type="image" src="qmb.png" name="saveForm" class="btTxt submit" id="button" height="49.5px" padding = "0px" />

Answer №1

Implementing with jQuery

$("#flowers").click(function () {
    var _this = $(this);
    var current = _this.attr("src");
    var swap = _this.attr("data-swap");
    _this.attr('src', swap).attr("data-swap",  current);
   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img id='flowers' class="full" src='http://www.rachelgallen.com/images/snowdrops.jpg' width="500" height="400" data-swap='http://www.rachelgallen.com/images/daisies.jpg'  width="500" height="400" />

Utilizing Javascript

img{height:400px; width:500px}
<script>
    function swap()
{
    if (document.pic.src=='http://www.rachelgallen.com/images/snowdrops.jpg'){

document.pic.src='http://www.rachelgallen.com/images/daisies.jpg';
} 
else if (document.pic.src=='http://www.rachelgallen.com/images/daisies.jpg'){

document.pic.src='http://www.rachelgallen.com/images/snowdrops.jpg';
}
}
</script>
<img src="http://www.rachelgallen.com/images/snowdrops.jpg" name="pic" onclick="swap()"/>

Using only mouseover/mouseout events

img{height:400px; width:500px}
<img src="http://www.rachelgallen.com/images/daisies.jpg" 
onMouseOver="this.src='http://www.rachelgallen.com/images/snowdrops.jpg';"
onMouseOut="this.src='http://www.rachelgallen.com/images/daisies.jpg';">

Answer №2

For those who prefer using pure JavaScript over jQuery, here is a simple code snippet to toggle an image:

<input type="image" id="button" name="img" src="firefox.ico" width="50" />
<script>
    document.getElementById("button").addEventListener("click", function(){
        this.setAttribute("src", (this.getAttribute("src") === "firefox.ico") ? "chrome.ico" : "firefox.ico");
    });
</script>

While Rachel's approach with pure JavaScript is valid, some may find this method to be more user-friendly and easier to understand. It's generally recommended to avoid using the onclick property in HTML and instead utilize event listeners in JavaScript for better control and organization.

Answer №3

When you use Jquery and click for the first time, the class 'clicked' will be added.

$(document).ready(function(){
$('button').on('click', function(){
$(this).toggleClass('clicked');
});
});

Here is the accompanying CSS:

Button{
Background: url(img1.jpg);

}
Button.clicked{
Background: url(img2.jpg);
}

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

What is the best way to relocate a form to the top of the page

I am creating a website to enhance my HTML skills, and I encountered an issue with the sign-in form. Whenever I try to place an image next to the form, it automatically moves to the bottom. I have attempted using padding-top and padding-bottom but to no av ...

What is the best way to eliminate the underline text decoration from a link element?

Take a look at this JS Bin. I want to change the link Project name in there. By default, it is underlined when hovered over. How can I remove that effect? I attempted using a class project-name: a:hover, a:focus .project-name { text-decoration: non ...

Defaulting summernote to display in italics

Looking for a way to italicize a series of summernote inputs by default? I have removed all toolbar options except the italics button. Here's the HTML generating these inputs: <div style="width:250px;"> < ...

The scrolltop function is dysfunctional on CentOS operating systems

I'm currently working on implementing smooth scrolling functionality when a button is clicked. The feature works perfectly fine with a local Apache server and IE10+, but when the project is deployed on "CentOS", it doesn't work on the same browse ...

When using a custom selection color to highlight underlined text, the underline becomes invisible

I am currently working on a website where I want to customize the text selection color. ::selection { background-color:#00ffff; } However, there seems to be an issue in this specific situation: p::after { content:"Try selecting the above elemen ...

What could be causing my <UL> to not properly expand around the <LI> items inside of it?

I am currently working with WordPress and have created a menu using a list structure. Here is an example of how it looks: <ul> <li>Home</li> <li>About</li> <li>ParentItem <ul> <--- The heig ...

Are there alternative methods to retrieve the CSS properties of web elements more effectively than relying on selenium?

I have a situation in my code where I need to retrieve the CSS properties of a large number of web elements. Currently, I am using Selenium and the code looks like this: ... node = browser.find_element_by_xpath(xpath_to_node) return {k: node.v ...

Bootstrap offers an improved method for arranging elements in columns and rows, especially when you need to omit certain ones

Is there a more efficient method for aligning elements using Bootstrap? Here is my current approach: <div className="row"> <div className="col-3 font-weight-bold"> Item Name ...

Use XMLHttpRequest to load and display a PDF file within the web browser

Can XMLHttpRequest be used to send the filename by POST method and open a PDF in the browser? xmlhttp.open("POST","pdf.php",true); //CHANGE xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send("file="+input); ...

Using Sass to create dynamic variables with other variables

Is it possible to reference variables based on the value of another variable? This functionality exists in languages like PHP. For example, in Sass: I have variables $green, $blue, and $yellow being included from a partial. I want to dynamically set the ...

The table's style is not rendering properly with lengthy names

Seeking assistance with styling a table on my website. Please take a look at my website. If you search for "Rochester, mn" and scroll down, you'll notice that for long names like Tilson's Automotive and Goodyear, the text falls below the image in ...

Enhanced security by implementing longer cipher length for AES encryption using Integer array

Within this code snippet, I have utilized an integer array to carry out AES encryption. The input consists of an integer array with a size of 16 elements. Upon encryption, the resulting cipher byte[] size is 64. It's worth noting that each integer occ ...

jQuery is malfunctioning following an AJAX request

Can anyone help me fix an issue with my jQuery code? I have a hidden div that should be shown when the mouse hovers over a sibling element. However, it seems like after my AJAX function is executed, the jQuery stops working. <div class="parent"> ...

Tips on overriding the outline:none property in CSS

Is there a way to overwrite the 'outline: none' property in CSS? I have a parent class that has this property set, but I want to remove it in the child class. ...

Using jQuery to dynamically populate a list with the information from a JSON dataset

How can I utilize JSON data to ensure that jquery populates the correct ul in this code snippet, creating 5 ul and populating them with li elements? Expected output: The slides should be assigned to specific modules as indicated in the JSON data, instead ...

Conceal Primeng context menu based on a certain condition

I'm struggling to prevent the context menu from showing under certain conditions. Despite following the guidelines in this post, the context menu continues to appear. My goal is to implement a context menu on p-table where it should only show if there ...

What is the method for obtaining the div ID's from this form?

This is the scenario I am working on: my app takes the text inputted by the user and exports it to a specific website that contains similar elements. For example, if the user enters a title in the app and clicks a button, the app will transfer that value t ...

Incorporating jQuery functions in the Angular app's main component file, app

I've been working on an Angular application and recently added the jQuery package with the following code: $ npm install jquery --save Now, I am attempting to transfer data from my HTML web page's .js file to the app.component.ts in Angular. I ...

What is the most effective way to show an error message within the login form itself?

I'm currently dealing with a dilemma involving my login.php and login_process.php files. The login form is in the former, while the validation process occurs in the latter. I'm struggling to figure out how to display error messages on the login f ...

The carousel's slides don't behave properly when swiping or using the slider controls (next/prev)

I have recently completed the construction of a carousel with swipe/touch functionality and control buttons for previous and next slides. However, I am facing an issue with the behavior of the carousel as it seems to be sliding by 2 or 3 instead of one at ...