Link to home
Start Free TrialLog in
Avatar of Cerixus
CerixusFlag for United States of America

asked on

Modify CSS style globally with javascript?

I have a page with a bunch of fields.  I want to put a little edit button next to them.  There will probably be a dozen or so.  However, I don't want them there the entire time.  I would like some sort of "Toggle Edit" button that would show/hide all the individual edit buttons.  I've found some js to modify the style of an individual element using "GetElementByID" or "GetElementsByName" or whatever, but what I actually want to do is change the STYLE.  For instance, I might have 15 divs with a class of "Edit" applied and Display: none.  When someone clicks "Toggle Edit" I want to change "Edit" to Display: inline.
Avatar of Gurvinder Pal Singh
Gurvinder Pal Singh
Flag of India image

you can get the handle to an element, and change its style

var element = document.getElementById("elementId");
element.style.display = "none"; //or block

Avatar of wellhole
wellhole

Something like this?
if(document.styleSheets){
var sheet = document.styleSheets[0]
if(sheet){
var ssRules = sheet.cssRules ¦¦ sheet.rules;
if(ssRules){
var result = null;
for(var c = 0; c < ssRules.length;c++){
if(ssRules[c].selectorText == ".javascript_only"){
result = ssRules[c].style;
break;
}
}
if(result){
result.display = "block";
}
}
}
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Gurvinder Pal Singh
Gurvinder Pal Singh
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sounds like you need to start using jQuery. http://api.jquery.com/css/

With jQuery you could access all the elements with the 'Edit' class applied to them and change their css style like this:

$('.Edit').css('display', 'none');
I think you're on the right track.
I would use jQuery just to make life easier, if you are not already using it on the site it would be as simple as including the file inside the <head>.
Then, to do what you are talking about you should be able to do something like this:

<style type="text/css">
	.MyClass {display:none;}
	.MyNEWClass {display:block;}
</style>

<script type="text/javascript">
    function changeClass()
    {
       // this adds the class MyNEWClass to the elements with a class of .MyClass
      $('.MyClass').addClass('MyNEWClass');
    }

       // this is just a click listener, it does not need to look exactly like this
    $(':button:contains(A Button)').click(changeClass);
</script>

<!-- button to show or hide the edit buttons -->
<button>A Button</button>

<!-- edit buttons to show or hide -->
<div class="MyClass">Edit Buttons</div>
<div class="MyClass">Edit Buttons</div>
<div class="MyClass">Edit Buttons</div>

Open in new window


You can add multiple classes, styles overwrite each other in order. You could use the removeClass() call but if you remove the class you are searching by then you will get stuck. It might be better to start your elements out with two classes, use one to "search" by and one to remove or add. (to give an element more than one class just separate the classes with a space like this <div class="ClassOne ClassTwo"></div>)

You could also make use of these to accomplish the same outcome:
      $('.MyClass').removeClass('MyNEWClass');
      $('.MyClass').toggleClass('MyClass');

Good luck!
Avatar of Cerixus

ASKER

I like the JQuery idea and I am using it for other stuff, but I'm not very good with javascript at all.  Right now I have a checkbox that I'm trying to use as the toggle.

<div class="ToggleEditMode"><asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" />Edit Mode</div>

How would I modify your example of the "button" click listener to make it work with a check box?  Also, does this method require a postback or would it render the client side changes immediately?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Using

$(".ToggleEditMode input[type='checkbox']").bind("click", function(){
   $(this).parent(".ToggleEditMode").toggle();
})

Is much better than the if/else statement, it works with the click like you want.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Cerixus

ASKER

Okay I'm having trouble following all of this and putting it together and getting it to work.  I have attached the JS, asp/html and CSS.  What am I missing?  Also, does it require a postback or should it just do it immediately?
CSS:

.Edit               {padding-left: 2px; display: none;}
.Show               {display: inline;}

Open in new window

JAVASCRIPT:

<script language="javascript" type="text/javascript">
   if($("#CheckBox1").attr("checked"))
   {
       alert("Test");
       $('.Edit').addClass('Show');
   }
   else
   {
       $('.Edit').removeClass('Show');
   }
</script>

Open in new window

ASP:

<div class="ToggleEditMode"><asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="False" />Edit Mode</div>

Open in new window

Avatar of Cerixus

ASKER

This one also didn't seem to work, but I like it best for it's simplicity:

$(document).ready(function()
{
         //Add javascript click event handler to CheckBox1
        $('#CheckBox1').click(function()
         {
                  //Change all elements using 'Edit' class to 'display: none' or 'display: inline' based on check state
                 $('.Edit').('display', this.checked ? 'inline' : 'none');
         });
});
not sure if CheckBox1 is the correct id of the checkbox, please check the same in view source
Ok, made a quick example for you so you can see it working:
 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="PlantMatrix.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .Edit { color: Blue; display: none; }
    </style>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function ()
        {
            $('#CheckBox1').click(function ()
            {
                $('.Edit').css('display', this.checked ? 'inline' : 'none');
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:CheckBox ID="CheckBox1" runat="server" Text="Show Edit Buttons" />
        <br />
        <asp:Button ID="Button1" runat="server" Text="Edit 1" CssClass="Edit" />
        <asp:Button ID="Button2" runat="server" Text="Edit 2" CssClass="Edit" />
        <asp:Button ID="Button3" runat="server" Text="Edit 3" CssClass="Edit" />
    </div>
    </form>
</body>
</html>

Open in new window

I just tested this, it works well. Give it a try!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-latest.min.js'></script>

<style type="text/css">
	.Edit {padding-left: 2px; display: none;}
	.Show {display: inline;}
</style>
	<script type="text/javascript">
	$(document).ready(function(){
		
		// Add onclick handler to checkbox w/id checkme
	   $("#CheckBox1").click(function(){
		
		// If checked
		if ($("#CheckBox1").is(":checked"))
		{
			//show the hidden div
			$(".Edit").show("fast");
		}
		else
		{	   
			//otherwise, hide it 
			$(".Edit").hide("fast");
		}
	  });
	
		});
	 </script>


</head>

<body>

<div class="ToggleEditMode">

<input type="checkbox" ID="CheckBox1" runat="server" AutoPostBack="False" />Edit Mode</div>

<div class="Edit">EDIT BUTTON</div>
<div class="Edit">EDIT BUTTON</div>
<div class="Edit">EDIT BUTTON</div>
<div class="Edit">EDIT BUTTON</div>
</body>
</html>

Open in new window

gurvinder372: "not sure if CheckBox1 is the correct id of the checkbox, please check the same in view source"

Yes, didn't think about this possibility.  If you are using a master/content page setup, then controls on your content pages will have big prefixes on their ID's looking something like this:

 ctl00_ContentPlaceHolder1_CheckBox1

Which would cause the javascript to fail.

A work around for this would be changing the $('#CheckBox1') to $('[id*="CheckBox1"]')

Making the javascript now look like this:

$('[id*="CheckBox1"]').click(function ()
{
        $('.Edit').css('display', this.checked ? 'inline' : 'none');
});
Avatar of Cerixus

ASKER

This works perfectly!

$(document).ready(function()
{
        $('.ToggleEditMode input').click(function()
         {
                 $('.Edit').css('display', this.checked ? 'inline' : 'none');
         });
});