turning CSS on / off globally - javascript

My goal is to have a button (controlled by a javascript function) that would toggle the entire CSS on the website on and off. I thought this was a common practice and was surprised when I couldn't find a complete solution here or on the web.
Here is what I got.
$("#button").click(function() {
var css = (document.styleSheets[0].enabled = true);
if (css == true)
{
document.styleSheets[0].disabled = true;
css = (document.styleSheets[0].enabled = false);
}
else if (css == false)
{
document.styleSheets[0].disabled = false;
}
});
A simple Jquery function that targets the button by ID and performs an if test. I could've ommited the variable, but this way I am able to check the value easily in console.log. I am able to turn the CSS off, but not back on. The program doesn't even get to the else condition.
I am aware that the else if is not really appropriate, but with just else (and even just with another if condition) the function doesn't run at all.
Second option that I thought of, and which might be much easier is just dynamically changing the contents of the link href attribute, where the path to the css file is given.
But I am struggling to target the href element with Javascript.

This is a simple Boolean toggle so write it as a simple toggle
$("#button").click(function() {
var sheet = document.styleSheets[0];
sheet.disabled = !sheet.disabled;
});
As for why your code isn't working as is,
var css = (document.styleSheets[0].enabled = true);
// same as
var css;
document.styleSheets[0].enabled = true;
css = true;
which means
if (css == true)
// same as
if (true == true)
which always holds so you'll always follow this code path

Well, for one you need to loop through all of the stylesheets.
Also, you can save some lines of code by using a counter, then on each button click increment the counter and use the % modulo operator to turn that into a 1 or a 0, which you can then coerce a boolean from using !!.
var count = 0;
var sheets = document.styleSheets;
$("#button").click(function() {
for(var i in Object.keys(sheets)) sheets[i].disabled = !!(++count % 2);
});
.demo {
background: #888;
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="demo">Some Text</div>
<button id="button">Click It</button>

Your problem is that you are doing an assignment when you should be doing an equality check.
You have
var css = (document.styleSheets[0].enabled = true);
But you are really trying to do an equality check, i.e.,
var css = (document.styleSheets[0].enabled == true);
Notice the extra =. The single = does an assignment, so your current code is equivalent to this:
document.styleSheets[0].enabled = true
var css = document.styleSheets[0].enabled; // i.e., true
Because you set enabled to true, your if (css == true) condition is always satisfied, so your code always turns the CSS off and never turns it back on.
The fix, as Paul S. wrote in his answer, is just to toggle the value of document.styleSheets[0].disabled, as in:
$("#button").click(function() {
document.styleSheets[0].disabled = !document.styleSheets[0].disabled;
});
There's no need to set and track a new property enabled.

The issue seems to be that you are doing assignment, and not comparison, on this line:
var css = (document.styleSheets[0].enabled = true);
It should be
var css = (document.styleSheets[0].enabled == true);
Probably simpler, since you have a jquery tag on the question, to just do:
$stylesheets = $('link[rel="stylesheet"]');
$("#button").click(function() {
$stylesheets.attr('disabled', !$stylesheets.attr('disabled'));
});

If you want to modify every href in your DOM,
just use
$('a[href*=]').each(function () {
var $this = $(this);
$this.attr('href', $this.attr('href').replace();
});

Related

How to set a JS variable from a CSS style

I've made a bunch of JavaScript functions to show, hide and populate various elements on a zooming menu. All seem to working except for one which I need the function to only run if a CSS setting is a specific value (width of 195%). I am very new to JavaScript so there may be more than one issue here.
<script>
function zoomShowF2() {
var widthNow = document.getElementById('svg1').style.width;
if widthNow = '195%' {
document.getElementById('zoomTitle').style.display = 'flex';
else
document.getElementById('zoomTitle').style.display = 'none';
}}</script>
You need to use comparison operators write the if statement as follows
if (widthNow == '195%') {
as the single = is assigning the value not comparing it
There are a few issues with your syntax:
function zoomShowF2() {
var widthNow = document.getElementById('svg1').style.width;
if (widthNow === '195%') {
document.getElementById('zoomTitle').style.display = 'flex';
} else {
document.getElementById('zoomTitle').style.display = 'none';
}
}
Thanks everyone. It works now with a combination of the changes suggested. I assume my curly braces are all in 'tidy' positions?
EDIT. I've adjusted the curly brace positions to as per Ed's layout.
Thanks all!
Your code does not called when the element changes it size or width. You must put all your code inside window.onresize event.
var displayOutput = document.getElementById("display-option");
function reportWindowSize() {
displayOutput.text = document.getElementById("element-to-check").style.width;
}
window.onresize = reportWindowSize;
<p id="element-to-check">Resize the browser window to fire the <code>resize</code> event.</p>
<p>Display: <span id="display-option"></span></p>

Trying to change the color of text on click in javascript

So I am trying to make something where whenever I click on the text it change's color.
Javascript:
function changecolor(){
var tc = document.getElementById("header").style.color.value;
if (tc = "#000000") { tc = "#0009FF"}
else if (tc == "#0009FF") { tc = "#FF0000"}
else if (tc == "#FF0000") { tc = "#15FF00"}
else if (tc == "#15FF00") { tc = "#FFA600"}
else {tc = "#000000"};
document.getElementById("header").style.color.value = tc;
}
html:
<div onclick="changecolor()"><h1 id="header" style="color:#000000;"> Nick's Basic Physic's Calculator </h1></div>
It is not working and I have not been able to figure out why. When I click on the text nothing happens.
Change
document.getElementById("header").style.color.value = tc;
to
document.getElementById("header").style.color = tc;
Working example:
http://jsfiddle.net/xEyLf/
your problem is in var tc = document.getElementById("header").style.color.value;
you have to change to tc = document.getElementById("header").style.color;in order to get the color into variable.
I have another solution... here's a jsfiddle: http://jsfiddle.net/9zfJA/
Keep in mind I'm using these jQuery methods (as well as the jQuery library itself), by simply switching between CSS classes:
hasClass(): to check if the class is present
addClass(): to add the correct class based on the condition above
removeClass(): remove all classes, I've basically built a "reset" function
I think there are errors in the way it functions and how you want it, but I've built it on the same logic you have in your question.

enable disable stylesheet using javascript in chrome

Rephrase of question: What is the best way to provide alternate stylesheets for a document?
I have a list of stylesheets, all of which are referenced in the html file.
I use javascript to disable all but one file.
example:
style1 disabled = false
style2 disabled = true
In practice, the last stylesheet to load (style2) is the active one, regardless of the disabled property.
How can I alternate between stylesheets on a document in chrome?
I tried to set the value of href attribute, but it seems to be read only.
example of code I have been using: (I am using an object called MenuStyles that is storing various css information)
function setActiveStyleSheet(name) {
var selectedSheet;
var currentSheet;
for (var i = 0; i < MenuStyles.styleSheets.length; i++) {
currentSheet = MenuStyles.styleSheets[i];
if (currentSheet.name === name) {
selectedSheet = currentSheet.sheetObj;
currentSheet.disabled = false;
} else {
currentSheet.disabled = true;
}
}
return selectedSheet;
}
EDIT: it turns out the problem was due entirely to bugs in the code. disabled property works fine. below is the fixed function:
function setActiveStyleSheet(name) {
var selectedSheet;
var currentSheet;
for (var i = 0; i < MenuStyles.styleSheets.length; i++) {
currentSheet = MenuStyles.styleSheets[i];
if (currentSheet.name === name) {
selectedSheet = currentSheet.sheetObj;
currentSheet.sheetObj.disabled = false;
} else {
currentSheet.sheetObj.disabled = true;
}
}
return selectedSheet;
}
In general you'd subclass off the BODY tag and use a single stylesheet that uses these classes. Then just swap the BODY class, not the sylesheet. Otherwise, you should be doing this server-side.
<body class="sheet1">
then
sheet1.h1 {
...
}
sheet2.h1 {
...
}
If you know the order of your stylesheets you can use-
document.styleSheets[i].disabled=true or
document.styleSheets[i].disabled=false;
If you have 2 stylesheets you can toggle between them with-
var S=document.styleSheets;
if(S[0].disabled){
S[0].disabled=false;
S[1].disabled=true;
}
else{
S[1].disabled=false;
S[0].disabled=true;
}
Current browsers offer reasonable ability to dynamically enable/disable stylesheets through the use of either the 'disabled' DOM property (Gecko) or by adding/removing the disabled attribute (Webkit and IE).
Unfortunately, these approaches only reliably work on 'link' tags that reference an external stylesheet (not 'style' tags), unless you are using IE10+. Yes - I said that - only IE does the right thing here.
For inline CSS using 'style' tags on non-IE browsers, you need to find a more crude way to enable/disable like those discussed above (remove the style element, etc).
I was able to get this to work with setting the disabled property and by including a 'title' attribute the stylesheets.
title property makes the stylesheet PREFERRED rather than PERSISTENT. see http://www.alistapart.com/articles/alternate/
I've found a great way (IMHO) to achieve this:
Let's suppose you know the exactly order of your stylesheet. Let's say you want to alternate stylesheet 0 and 1 (first and second):
To get a stylesheet state (enabled/disabled) you can try this (i.e. testing the second one):
document.styleSheets[1].disabled
...and it returns trueor false.
So to alternate you can write this code in an onclick event:
document.styleSheets[0].disabled = !(
document.styleSheets[1].disabled = !(document.styleSheets[1].disabled)
);
HTH!
For me if the link is disabled, document.styleSheets does not return the link in the collection ( in Chrome) . Only the enabled links are returned.
I use document.head.getElementsByTagName('LINK'), to get them all, out of HEAD.
Like:
private changeStyle(styleName: string): void {
const links = document.head.getElementsByTagName('LINK');
for (let i = 0; i < links.length; i++) {
const link = links[i] as any;
if( !link.href) continue;
if (link.href.indexOf(styleName) === -1) {
link.disabled = true;
} else {
link.disabled = false;
}
}
}

Class of ID Change based on URL - URL Based Image Swap -

What I'm trying to achieve:
Based on URL (ie., foo.com/item1), the div element "logoswap" receives a different class.
The following is the code I put together but it seems completely wrong. I'm not a JS pro by any means, XHTML/CSS is more my speed (some PHP)... I cannot use PHP, even if it is possible in PHP (and I know it is because I have a PHP version of what I need done already, but I can't call the PHP properly.
I'm really just trying to get a different logo to show up based on the directory/url... It doesn't have to be a background element called in by the CSS class necessarily, I just need a different image to load based on the aforementioned url variable...
$(function() {
var url = location.pathname;
if(url.indexOf('item1') > -1) {
document.getElementById("logoswap").className += " class1";
}
elseif(url.indexOf('item2') > -1) {
document.getElementById("logoswap").className += "class2";
}
elseif(url.indexOf('item3') > -1) {
document.getElementById("logoswap").className += "class3";
}
elseif(url.indexOf('item4') > -1) {
document.getElementById("logoswap").className += "class4";
}
elseif(url.indexOf('item5') > -1) {
document.getElementById("logoswap").className += "class5";
}
else {
document.getElementById("logoswap").className += "class1";
}
});
That's what I have... Ugly I'm sure.
That's why I'm here though, I definitely need some help.
Assigning CSS Class By URL Pathname
A jsfiddle has been setup for
this solution.
Here is a case for using numeric expressions if they are available. This does not apply to the above question.
$(function() {
var rgx = /item(\d+)$/,
url = location.pathname,
id = (rgx.test(url)) ? url.match(rgx)[1] : '1';
$("#logoswap").addClass("class" + id);
});
UPDATE:
In light of the new details you may need an array of values, these should be derived from or exactly equal to the class names you intend to use.
$(function(){
// my favorite way to make string arrays.
var matches = "brand1 brand2 brand3".split(" "),
url = location.pathname.match(/\w+$/)[0], // get the last item
id = matches.indexOf(url),
className = matches[(id > -1) ? id : 0];
$("#logoswap").addClass(className);
});
To make this work you will need a few things in place. I will assume that the paths will end in a number as we have outlined here. The default ends with 1. You will need the images to be accessible. You need to define the styles for each possibility.
CSS Setup
#logoswap {
height : 200px;
width : 200px;
}
.class1 {
background-image : url(/path/to/default.jpg);
}
.class2 {
background-image : url(/path/to/second.jpg);
}
.brand1 {
background-image : url(/path/to/brand/1/logo.jpg);
}
...
Without jQuery
if you do not have jQuery in your code you may need to use window.onload.
(function(){
var old = window.onload;
window.onload = function(){
old();
var r = /item(\d+)$/,
url = location.pathname,
id = (r.test(url)) ? url.match(r)[1] : '1';
document.getElementById('logoswap').className += "class" + id;
};
})()
I just want to take a moment here to
encourage anyone who is doing this
type of code to get used to Regular
Expressions and learn them. They are
far and away the most frequently used
cross language part of my development
arsenal.
There's nothing that wrong with what you have. You could tidy it up with something like below.
$(function() {
var url = location.pathname;
var logo = document.getElementById("logoswap");
var i = 6;
logo.className = "class1";
while(i--)
{
if(url.indexOf("item" + i) > -1) {
logo.className = "class" + i;
}
}
});
Hope this helps.
Using just HTML/CSS, you could add (or append via javascript) an id to the body of the page:
<body id="item1">
Then in your CSS, create a selector:
#item1 #logoswap {
// class1 CSS
}

I need to set display: block on div then find an anchor within that div

I'm nearly finished with this project but I have been beating my head against this problem for a day or so.
Big picture:
Im trying to create a link that will jump between tabs and find an anchor.
Details:
I need to create a link which triggers the function that hides the current div (using display: none)/shows another div (display: block;) and then goto an anchor on the page.
My first intuition was to do:
code:
<a onClick="return toggleTab(6,6);" href="#{anchor_tab_link_name}">{anchor_tab_link_name}</a>
Since the onClick should return true and then execute the anchor. However it loads but never goes to the anchor.
Here is the toggleTab function to give some context:
function toggleTab(num,numelems, anchor, opennum,animate) {
if ($('tabContent'+num).style.display == 'none'){
for (var i=1;i<=numelems;i++){
if ((opennum == null) || (opennum != i)){
var temph = 'tabHeader'+i;
var h = $(temph);
if (!h){
var h = $('tabHeaderActive');
h.id = temph;
}
var tempc = 'tabContent'+i;
var c = $(tempc);
if(c.style.display != 'none'){
if (animate || typeof animate == 'undefined')
Effect.toggle(tempc,'appear',{duration:0.4, queue:{scope:'menus', limit: 3}});
else
toggleDisp(tempc);
}
}
}
var h = $('tabHeader'+num);
if (h)
h.id = 'tabHeaderActive';
h.blur();
var c = $('tabContent'+num);
c.style.marginTop = '2px';
if (animate || typeof animate == 'undefined'){
Effect.toggle('tabContent'+num,'appear',{duration:0.4, queue:{scope:'menus', position:'end', limit: 3}});
}else{
toggleDisp('tabContent'+num);
}
}
}
So I posted this on a coding forum and a person told me that my tab code was done in prototype.
And that I should "Long story short: don't use onclick. Attach the data to the A tag and handle the click event yourself (using preventDefault() or similar) to do your tab-setting stuff, then when it's done, manually set your location to the hash tag."
I do understand what he is suggesting but I don't know how to implement it because I don't know much about javascript syntax.
If you can provide any hints or suggestions it would be amazing.
Update:
I tried to implement the solution below like this:
The link:
<a id="trap">trap</a>
Then adding the following js to the top of the page:
<script type="javascript">
document.getElementById("trap").click(function() { // bind click event to link
tabToggle(6,6);
var anchor = $(this).attr('href');
//setTimeout(infoSupport.gotoAnchor,600, anchor);
jumpToAnchor();
return false;
});
//Simple jump to anchor point
function jumpToAnchor(){
location.href = location.href+"#trap";
}
//Nice little jQuery scroll to id of any element
function scollToId(id){
window.scrollTo(0,$("#"+id).offset().top);
}
</script>
But unfortunately it simply doesn't seem to work for me. When I click the text simply nothing happens.
Anyone notice any apparent mistakes? I'm not used of working with javascript.
I found a lot simpler solution:
$(function(){
jumpToTarget('spot_to_go'); //This is what you put inside your function when the link is clicked.
function jumpToTarget(target){
var target_offset = $("#"+target).offset();
var target_top = target_offset.top;
$('html, body').animate({scrollTop:target_top}, 500);
}
});
Working demo:
http://jsbin.com/ivure/3/edit
So on the click event you do something like this:
//Untested
$('#trap').click(function(){
tabToggle(6,6);
var anchor = $(this).attr('href');
jumpToTarget(anchor);
return false;
});
​
Apparently a small delay was all I needed.
I used this for the link. This is preferred for my situation since I'm batch generating many of these links.
trap
Then I used this vanilla javascript
//Simple jump to anchor point
function jumpToAnchor(target){
setTimeout("window.location.hash=target",450);
}
This loads the link and instantly goes to the location. No jerkiness or anything.

Categories

Resources