Using JQuery to change HTML button image causes styling issues

285
November 26, 2016, at 8:08 PM

I have a standard HTML button which triggers some Ajax when pressed. I'm using JQuery to disable the button and display a progress GIF while I'm awaiting the return.

For some reason setting the background image of the button causes it to lose other styling and go out of alignment with its neighbours.

I've tried wrapping it in divs, setting all sorts of margins and positions and I can't get it to work.

Any suggestions?

FYI: I have no problem using <input> instead of <button> if that's easier.

Broken:

Fixed:

Code:

var mybutton = $('#MyButton'); 
 
if (mybutton) 
{ 
    mybutton.click(function() { 
 
        // Disable 
        mybutton.prop('disabled', true); 
         
        // Hide text 
        mybutton.html(''); 
         
        // Set image 
        mybutton.css("background", "url('http://lorempixel.com/32/32/') no-repeat 32px center"); 
         
        // Wait 5 seconds to simulate slow Ajax return 
        setTimeout(continueExecution, 3000); 
    }); 
}; 
 
function continueExecution() 
{ 
    // Reset button back to normal 
    mybutton.html('Check'); 
    mybutton.css("background", ""); 
    mybutton.prop('disabled', false); 
};
#Label_Guid{ 
font-size: 20px; 
} 
#Textbox_Guid{ 
    width: 200px; 
    height: 30px; 
    margin-left: 5px; 
    margin-right: 5px; 
} 
#MyButton{ 
    height: 40px; 
    width: 100px; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<span id="Label_Guid">GUID:</span> 
<input id="Textbox_Guid" type="text" name="guid"> 
<button id="MyButton">Check</button>

Answer 1

The only thing you need to do is add the css to your button:

vertical-align: middle;

Your issue isn't coming from the background image, or the disable, it's because there is no content in the button. Without content, the default vertical alignment is changing its position.

READ ALSO
Jquery plugin click events

Jquery plugin click events

I've been learning and trying to create my own jQuery plugin by following examples and tutorials online

445
Keep initial value in textbox after click

Keep initial value in textbox after click

I need to keep an initial value/placeholder in my textbox after it's clickedIt needs to be readonly but allow the user to add characters in after the preset text:

254
Bootstrap stacked nav only one open at a time issue

Bootstrap stacked nav only one open at a time issue

I have a stacked bootstrap nav menu, and what I would like for it to operate like an accordionIf a user clicks one of the nav containers, I'd like for the rest of them to close

212
JQuery get &#39;id&#39; attribute

JQuery get 'id' attribute

So I have the following code that generates a table and applies a click function to each td within the tableIt also applies an incremental id starting with 1

390