Carlos Santiago
Carlos Santiago

Reputation: 15

Show image next to input rather than underneath it

So, I wanted to display a loading gif when an input box was on focus.
I've managed to do it but the loading gif it's getting below the input box, and not after On CSS, if I change the display:none to display:yes the loading gif appears after the input box as I want, but only until the JS function is triggered.

var input = document.getElementById('showloading');
var message = document.getElementsByClassName('loadingGif')[0];
input.addEventListener('focus', function() {
  message.style.display = 'block';
});
input.addEventListener('focusout', function() {
  message.style.display = 'none';
});
.loadingGif {
  display: none;
}
<input id="showloading" type="text" class="auto">
<img class="loadingGif" src="loading.gif">

Screenshoots:

What it looks like:

What it looks like

What I want it to look like:

What I want it to look like

Upvotes: 1

Views: 101

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074148

The problem is that block is displayed as a block, so it starts a new visual line.

I wouldn't use style at all, I'd use a class to show/hide the image:

var input = document.getElementById('showloading');
var message = document.getElementsByClassName('loadingGif')[0];
input.addEventListener('focus', function() {
  message.classList.remove("hide"); // <===
});
input.addEventListener('focusout', function() {
  message.classList.add("hide"); // <===
});
.loadingGif.hide {
/* --------^^^^^   */
  display: none; /* <=== */
}
<input id="showloading" type="text" class="auto">
<img class="loadingGif hide" src="loading.gif">
<!-- ------------------^^^^   -->

...although as Pepper says (and Diogo also now says), you can do this with just CSS and without JavaScript or a class.

Upvotes: 3

Diogo Peres
Diogo Peres

Reputation: 1372

@T.J. Crowder aswer is the one you should follow if you want to use Javascript although you don't need Javascript to do what you want. You can use only CSS by using :focus selector and the sibling selector + to write a style rule. When showloading is focused all the adjacent siblings with the class loadingGif will have the display: inline-block

Such as:

.loadingGif {
  display: none;
}
	
#showloading:focus + .loadingGif {
  display: inline-block;
}
<input id="showloading" type="text" class="auto">
<img class="loadingGif" src="loading.gif">

Upvotes: 4

Related Questions