Reputation: 298
How to create a toggle button to add inline styles?
For example in this simple structure i want to make a toggle button to show or hide the div I do not want to add a class name or using only .show() and .hide() in jQuery
I need it to be Inline style for example If i toggle the button i want it to add this style
style="display:block color:red;"
and if you toggle again
style="display:none"
<button>toggle</button>
<div>blah bla blah</div>
Upvotes: 2
Views: 3081
Reputation: 10937
simplified toggle version
div.style.display=div.style.display==='none'?'block':'none';
snippet
var button=document.getElementById("button");
var div=document.getElementById("div");
button.onclick=function (){
div.style.display=div.style.display==='none'?'block':'none';<-----single line
}
<button id="button">toggle</button>
<div id="div">blah bla blah</div>
Upvotes: 0
Reputation: 4584
You can check toggle style with .css("display")
.Then set attribute as you wanted to do
$("button").click(function(){
if($("div").css("display") == "none") {
$("div").css({"display":"block","color":"red"});
}
else{
$('div').css("display","none");
}
});
Upvotes: 1
Reputation: 2056
try below code...
<button id="button">toggle</button>
<div id="div">blah bla blah</div>
JavaScript code...
var button=document.getElementById("button");
var div=document.getElementById("div");
div.style.display="block";
button.onclick=function (){
if(div.style.display=="block"){
div.style.display="none";
}
else{
div.style.display="block";
}
}
live demo here
Happy coding... :)
Upvotes: 3
Reputation: 32354
Use custom classes and toggleClass()
.costomclass {
display:block color:red;
}
.normalClass {
display:none
}
<div class="normalClass">blah bla blah</div>
$(function(){
$('button').click(function(){
$('.normalClass').toggleClass('costomclass');
});
});
Upvotes: 0