Modify the button background image, text, and shape simultaneously when hovered

Can a button's background image or text change, along with its shape, when hovered over using CSS, JS, or both?

For example, if I have a button displaying a checkmark symbol ✓ and I want it to transform from a circle shape to a rectangle shape, and the text to change from the checkmark to the word submit on mouse hover, is this achievable?

Is there a way to achieve this effect through CSS, JS, or a combination of both?

Answer №1

Customize without Altering Animations

Check out this JSFiddle link for reference.

If the goal is to modify the background image and shape only, CSS can be utilized:

.button {
    height:30px;
    width:60px;
    -webkit-border-radius:15px;
    -moz-border-radius:15px;
    border-radius:15px;
    background-image:url(...)
}
.button:hover {
    -webkit-border-radius:0px;
    -moz-border-radius:0px;
    border-radius:0px;
    background-image:url(...)
}

For text changes, JavaScript comes into play:

<style>
    #button {
        height:30px;
        width:60px;
        border-radius:15px;
        background-image:url(img1.png);
    }
</style>
<script>
    function mouseOver() {
        document.getElementById("button").style.backgroundImage = "url(img2.png)";
        document.getElementById("button").style.borderRadius = "0px";
        document.getElementById("button").innerHTML = "Submit";
    }

    function mouseOut() {
        document.getElementById("button").style.backgroundImage = "url(img1.png)";
        document.getElementById("button").style.borderRadius = "15px";
        document.getElementById("button").innerHTML = "✓";
    }
</script>

<div id="button" onmouseover="mouseOver()" onmouseout="mouseOut()">✓</div>

Incorporating Transition Effects

Explore this JSFiddle link for demonstration.
To animate the button effectively, include the following CSS properties:

-webkit-transition:all 0.2s;
transition:all 0.2s;

Additional classes like .fade-out and .fade-in can be added for more complex animations:

.fade-out {
    opacity: 1;
    animation: fadeOut 0.2s;
}
.fade-in {
    opacity: 0;
    animation: fadeIn 0.2s;
}

Introduce @keyframes animations in your CSS to handle fading effects smoothly.

@keyframes fadeOut {
    from {opacity: 1;}
    to {opacity: 0;}
}
@keyframes fadeIn {
    from {opacity: 0;}
    to {opacity: 1;}
}

The script then integrates JavaScript functions for a sophisticated user experience:

function mouseIsOver() {  
    btn = document.getElementById("button_java");
    btn.childNodes[0].className += ' fade-out';
    // More functionality here based on requirements
}

function mouseIsOut() {
    // Functionality for mouse out event
}
  • childNodes[0]: Retrieves inner children elements
  • className += ' fade-out': Adds specified class without altering existing ones
  • setTimeout(function,waitduration): Delays execution of code snippet
  • className.replace(' fade-out',''): Removes targeted class from element's class list

Your Unique Button Design

View the customized button layout on JSFiddle or PasteBin
Enhance the button appearance with additional styles and jQuery integration:

.button p {
    line-height:1em;
    margin:0;
}

Remember to include jQuery library in your header section:

<script src="http://code.jquery.com/jquery-2.1.3.js"></script>

Add JavaScript code snippets for interactive hover actions:

<script type="text/javascript">
$( document ).ready(function() {
    // Handle hover interactions here
});
</script>

With these adjustments, you can create a personalized and visually appealing button for your website!

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

Stylish Fonts with Bootstrap 4 and Font Awesome

I've encountered a little issue. I'm attempting to horizontally center each icon within a div, but my attempts so far have been unsuccessful. <div class="row"> <div class="bg-inverse p-x-1 col-xs-12 default-1 "> <div clas ...

Achieve a seamless integration of a navbar and list on the same line by utilizing the power of Bootstrap

No matter how much I tried, I couldn't solve the problem of my list not appearing in the same line. I attempted using display: inline-block; and padding: 0, but to no avail. /* added by editor for demonstration purpose */ body { background-color: ...

Update the image source every 1 second with Jquery and Javascript

I've been experimenting with creating a script that dynamically changes the source of an image every two seconds based on a list. Essentially, my current approach involves using a for loop to iterate over the provided list: $(document).ready(functio ...

Merge web address when form is sent

I'm currently working on a search application using the Django framework and the Yelp API as my backend, which is functioning properly. However, I am facing some challenges with the frontend development, specifically integrating Leaflet.js. My search ...

How can you deduce the type from a different property in Typescript?

I have encountered obstacles in my development process and need assistance overcoming them. Currently, I am trying to configure TObject.props to only accept 'href' or 'download' if the condition TObject.name = 'a' is met, and ...

Listening for events on an array of elements using jQuery

My task involves populating an array with elements using the .each() method and the $(this) selector. (function($){ var elements = new Array(); var index = 0; $("img").each(function() { if($(this).attr("attribute")){ $(thi ...

Issues with Bootstrap's hamburger menu not functioning properly when clicked

Can't seem to get my hamburger button working. I've followed the bootstrap documentation and ensured that Bootstrap and jQuery are in the correct order, but still no luck. Any suggestions on what could be causing this issue? Are my links misplace ...

What are the steps for implementing CORS?

I recently attempted to set up Ajax calls and stumbled upon the following code snippet: <!DOCTYPE html> <html> <body> <p id="demo">Let AJAX update this text.</p> <button type="button" onclick="loadDoc()">Updat ...

Pressing an HTML button can enable and disable the pause and resume functions

Currently, I am working on an audio player where I need to implement functionality to pause and resume the playback. I have already set up the pause() and resume() functions in my script. The issue I am facing is related to the HTML button that triggers th ...

How can I make one object's position target another grouped object in three.js, while still enabling rotation to track a camera in augmented reality?

Currently, I am utilizing a cutting-edge augmented reality library that specializes in advanced image tracking capabilities. Despite extensively studying this project, I have reached a point where I require assistance. Essentially, the library generates an ...

Error in Node.js: Unhandled promise rejection due to undefined value

We're currently facing an issue with the create user controller in Node.js Express. The problem arises when attempting to sign up on the front end, resulting in an error message: "Unhandled promise rejection error value is not defined." Although it ap ...

What is the best way to display live data to multiple users with React and Firebase?

I'm working on a messaging app that needs to update in real-time. Currently, I have implemented the functionality to log in using Google, post messages, and display them on the screen. However, when another user logs in with a different Google account ...

Employing jQuery to add values dynamically into a text input field

On my Razor UI, I have a table with 3 columns displaying denomination, amount, and total amount: DEnom amt totalamt $1 0 0 $5 4 20 $10 1 10 $50 0 0 $100 2 200 Total 7 230 The denominations may change over time ...

Error message: JavaScript JSON variable undefined in AWS Lambda

My lambda function is being triggered by an IoT rule that sends a MQTT message in JSON format. I am facing an issue where the top level fields are logging correctly, but when it comes to nested objects in the JSON, they appear as "undefined". Even after tr ...

Tips for extracting data from div tags that share the same id

Html <!DOCTYPE html> <html> <body> <div id="one"> welcome <div class="two"> hello world </div> <div class="two"> bye world </div> < ...

Using VueJS to iterate through an array while applying a condition to filter out certain elements (combining v-for with v-if)

I'm currently working on a v-for loop to display two columns of card elements. The idea is to print the current element and the next one in a row if the index is even, skipping the elements with odd indexes. This is what my code looks like: <temp ...

After calling the use method in Express, utilizing the get method

const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use((req, res, next) => { console.log("Executing first middlewar ...

Sass compiling in Gulp not giving any error messages

I've encountered a puzzling issue with my gulp task for converting scss into css files: function css() { return gulp.src('src/scss/_index.scss') .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest('public/css&a ...

Unable to start initial Cucumber+javascript demonstration

I attempted to run the initial example provided in the official documentation found here. Using Windows 7x64 bit and node.js version 6.11 I ran the following commands but encountered the same outcome. * node_modules/cucumber/bin/cucumber.js autotests/c ...

MongoDB Query Fails to Fetch Documents with Matching Strings

I'm facing a peculiar issue where two seemingly identical strings are yielding different results in MongoDB. Below, I've pasted the two (seemingly distinct) strings with quotation marks on both sides (copied from Robo3T) to demonstrate any poten ...