Solved

Modify CSS style globally with javascript?

Posted on 2011-02-14
18
364 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
Comment Utility
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
Comment Utility
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
Comment Utility
0
 
LVL 40

Accepted Solution

by:
gurvinder372 earned 250 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
$(".ToggleEditMode input[type='checkbox']").bind("click", function(){
   $(this).parent(".ToggleEditMode").toggle();
})
0
 
LVL 3

Assisted Solution

by:thecrew
thecrew earned 125 total points
Comment Utility
This might help then:

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

-Logan
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 3

Expert Comment

by:thecrew
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
This works perfectly!

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

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This article discusses how to create an extensible mechanism for linked drop downs.
In this tutorial viewers will learn how to style transparent/translucent elements using alpha transparency in CSS Start with a normal styled element, such as a div.: Define its "background-color" property as "rgba (255, 255, 255, .5): The numbers in…
In this tutorial viewers will learn how to customize the background color and font color of highlighted text using the ::selection element in CSS Begin by defining the selected text as an element in CSS by typing "::selection": Style the ::selection…

728 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now