Reputation: 188
html:
<input id="myinput" class="cinput" type="image" src="http://www.foodwater.org.au/images/triple-spiral-3-small-button.jpg"/>
<br><br><br><br>
<button id="s">set to visible class</button>
<button id="h">set to hidden class</button>
<button id="db">set display:block</button>
<button id="dn">set display:none</button>
javascript:
$("#s").on("click", show);
$("#h").on("click", hide);
$("#db").on("click", db);
$("#dn").on("click", dn);
function show() {
document.getElementById("myinput").className = "cinputvis";
}
function hide() {
document.getElementById("myinput").className = "cinput";
}
function db() {
document.getElementById("myinput").style.display = "block";
}
function dn() {
document.getElementById("myinput").style.display = "none";
}
css:
.cinput {
position: absolute;
display: none;
top: 0px;
left 0px;
margin: 0px;
border: 1px solid black;
cursor: pointer;
}
.cinputvis {
position: absolute;
display: block;
top: 0px;
left 0px;
margin: 0px;
border: 1px solid black;
cursor: pointer;
}
So, If let's say i use the two buttons which change the element's class, I can toggle the button on and off, but once i use the other buttons to to manipulate the display property directly, I can't use any more the changing of className buttons to toggle them.
So I was wondering why is this happening ? Shouldn't changing the classname clear up everything and reassign the css directives ?
Upvotes: 2
Views: 1110
Reputation: 6855
You are using jQuery, why not going all the way:
$("#s, #db").on("click", function() {
$('#myinput').show();
});
$("#h, #dn").on("click", function() {
$('#myinput').hide();
});
No need for class names changing JavaScript, no need for CSS.
Upvotes: 1
Reputation: 2243
Inline styles (such as those set by JS, or those in a style="" block) have a higher priority than CSS classes. They will always, by design, trump inline styles, unless you use !important
on a style to override it.
Upvotes: 2
Reputation: 672
Change your code to this (JS):
function db() {
document.getElementById("myinput").className = "block";
}
function dn() {
document.getElementById("myinput").className = "none";
}
And add this two classes to CSS:
.none
{
display:none;
}
.block
{
display:block;
}
With document.getElementById("myinput").style.display = "block";
inline style was added to input and it cannot be removed when removing class which contains this style. Inline style must be removed separately.
Upvotes: 1
Reputation: 12213
Your classes are still changing but when you change display it overwrites the css rule from the class. So you have tochange it again back to the rule that the specific class has
Add
document.getElementById("myinput").style.display = "block";
to show()
function
and
document.getElementById("myinput").style.display = "none";
to hide()
function
Upvotes: 1