2

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>

4 Answers 4

3

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... :)

Sign up to request clarification or add additional context in comments.

1 Comment

It works fine, but i have used the jQuery one. Thanks :)
1

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");
        }
    });

1 Comment

Thats what i was looking for Thanks so much :)
0

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');
  });

});

1 Comment

Sorry, as i have mentioned i want it to be inline styles, but thanks :)
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.