Solved

Modify CSS style globally with javascript?

Posted on 2011-02-14
18
367 Views
Last Modified: 2012-05-11
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.
0
Comment
Question by:Cerixus
  • 5
  • 4
  • 4
  • +2
18 Comments
 
LVL 40

Expert Comment

by:gurvinder372
ID: 34889408
you can get the handle to an element, and change its style

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

0
 
LVL 9

Expert Comment

by:wellhole
ID: 34889432
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

0
 
LVL 40

Expert Comment

by:gurvinder372
ID: 34889434
0
Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 40

Accepted Solution

by:
gurvinder372 earned 250 total points
ID: 34889442
or you can assign a class to those elements and then fetch those elements by their class names in one go, and then change their display style
http://snipplr.com/view/1696/get-elements-by-class-name/
0
 
LVL 10

Expert Comment

by:P1ST0LPETE
ID: 34889452
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');
0
 
LVL 3

Expert Comment

by:thecrew
ID: 34889616
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!
0
 
LVL 1

Author Comment

by:Cerixus
ID: 34889675
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?
0
 
LVL 40

Assisted Solution

by:gurvinder372
gurvinder372 earned 250 total points
ID: 34889716
$(".ToggleEditMode input[type='checkbox']").bind("click", function(){
   $(this).parent(".ToggleEditMode").toggle();
})
0
 
LVL 3

Assisted Solution

by:thecrew
thecrew earned 125 total points
ID: 34889745
This might help then:

if($("#CheckBox1").attr("checked"))
{
    //do stuff
}
else
{
    //do different stuff (or nothing at all)
}

-Logan
0
 
LVL 3

Expert Comment

by:thecrew
ID: 34889770
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.
0
 
LVL 10

Assisted Solution

by:P1ST0LPETE
P1ST0LPETE earned 125 total points
ID: 34889955
Lets say all your buttons had the 'Edit' class applied like what you were talking about in your original post.

<asp:Button ID="EditButton1" runat="server" CssClass="Edit" />

Using your checkbox:

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

You could have jQuery on the page like this which would immediately make changes to the client's page without needing to do a postback:

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

There are several ways/variations to accomplish this task using jQuery.  Others have listed corrected ways of doing it as well.
0
 
LVL 1

Author Comment

by:Cerixus
ID: 34890175
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

0
 
LVL 1

Author Comment

by:Cerixus
ID: 34890269
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');
         });
});
0
 
LVL 40

Expert Comment

by:gurvinder372
ID: 34890325
not sure if CheckBox1 is the correct id of the checkbox, please check the same in view source
0
 
LVL 10

Expert Comment

by:P1ST0LPETE
ID: 34890377
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

0
 
LVL 3

Expert Comment

by:thecrew
ID: 34890452
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

0
 
LVL 10

Expert Comment

by:P1ST0LPETE
ID: 34890470
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');
});
0
 
LVL 1

Author Comment

by:Cerixus
ID: 34890495
This works perfectly!

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

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Building a website can seem like a daunting task to the uninitiated but it really only requires knowledge of two basic languages: HTML and CSS.
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
In this tutorial viewers will learn how to style rounded corners for elements in CSS using the border-radius property Begin with a normal styled element such as a div: To style all four corners of the div to be the same degree of roundness, use the …
In this tutorial viewers will learn how to embed custom externally-hosted Google Fonts using the Google Font API in CSS Go to the Google Fonts website at google.com/fonts: Browse or search based on font properties or name to find a suitable font for…

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question