javascript stylesheet changer not working - javascript

Ok a friend gave me this code, and it doesn't work. I have been looking for a java stylesheet changer, and this is the only one I can find. When I click on the link (to change the style) nothing happens. Help? And I do have trouble understanding javascript so it is difficult for me.
js code:
function setActiveStyleSheet(title) {
var i, a, main;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if(a.getAttribute("title") == title) a.disabled = false;
}
}
}
function getActiveStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
}
return null;
}
function getPreferredStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1
&& a.getAttribute("rel").indexOf("alt") == -1
&& a.getAttribute("title")
) return a.getAttribute("title");
}
return null;
}
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
window.onload = function(e) {
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
}
window.onunload = function(e) {
var title = getActiveStyleSheet();
createCookie("style", title, 365);
}
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
}
);
Header Stylesheet Code:
<link rel="stylesheet" type="text/css" media="screen" href="css/zerohour.css" title="default" />
<link rel="alternate stylesheet" type="text/css" media="screen" href="css/rainbow.css" title="rainbow" />
Link Activator Code:
<a href="#"
onclick="setActiveStyleSheet('default');
return false;">change style to default</a>
<a href="#"
onclick="setActiveStyleSheet('rainbow');
return false;">change style to rainbow</a>

Here is a re-write of what I think you are trying to do:
var activeStylesheet = (function() {
// Store title of default linked stylesheet
var defaultTitle;
return {
// Set the active stylesheet to the link styesheet element with title
// Set all others to disabled
setActive: function(title) {
var link, links = document.getElementsByTagName('link');
for (var i=0, iLen=links.length; i<iLen; i++) {
link = links[i];
if (link.rel.indexOf("style") != -1 && link.title) {
link.disabled = true;
if (link.title == title) {
link.disabled = false;
}
}
}
},
// Return the title of the currently active linked stylesheet,
// or undefined if none found
getActive: function() {
var link, links = document.getElementsByTagName('link');
for (var i=0, iLen=links.length; i<iLen; i++) {
link = links[i];
if (link.rel.indexOf("style") != -1 &&
link.title &&
!link.disabled) {
return link.title;
}
}
},
// Return the title of the link stylesheet element where
// rel property contains 'alt'
getPreferred: function() {
var link, links = document.getElementsByTagName('link');
for (var i=0, iLen=links.length; i<iLen; i++) {
link = links[i];
if (link.rel.indexOf("style") != -1 &&
link.rel.indexOf('alt') == -1 &&
link.title) {
defaultTitle = title;
return link.title;
}
}
}
};
}());
Some buttons to do stuff:
<button onclick="
alert(activeStylesheet.getActive());
">Show title of active stylesheet</button>
<button onclick="
activeStylesheet.setActive('rainbow');
">Set active stylesheet to "rainbow"</button>
<button onclick="
activeStylesheet.setActive('default');
">Set active stylesheet to "default"</button>
Note that using the title will be case sensitive, so be careful.
You can store the title of the default linked stylesheet in the defaultTitle variable, but I don't know what you want to do with it. You have a setPreferred that first checks that defaultTitle is set and if not, calls getPreferred, calls setActive with defaultTitle.

I realize that this question isn't tagged Jquery but unless you have a strong reason to stick with vanilla Javascript, I would recommend Jquery.
You can switch styles in just two lines of code:
$('#foobar').click(function(){
$('link').attr('href','newstyle.css');
return false;
});
Live Demo

Related

Shopify enable discount code in url (every page) - NO REDIRECT

IN SHOPIFY STORE: How to add discount code in URL without redirect with javascript. Having a parameter in the url with the discount code.
Every url in your website with the parameter discout will be activated in the checkout.
EXAMPLE OF USE
your discount code is DISCOUNTCODE1
www.myshopifywebsite.com/products/product1?discount=DISCOUNTCODE1
or
www.myshopifywebsite.com?discount=DISCOUNTCODE1
STEP 1
/* Put this in theme.liquid, preferably right before "</body>" inside a script tag */
//this code set the cookie
(function() {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
var product = urlParams.get('discount');
if (product != null && product.length > 1) {
document.cookie = 'discount=' + product + ';path=/';
}
})();
STEP 2
//Insert this code in cart-template.liquid or cart.liquid at the bottom of the page inside script tag
//Also, make sure your cart's "<form>" has an ID of "cartform".
/*Function to getcookie*/
function getCookie(nome) {
var name = nome + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ')
c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
(function() {
var discountCookie = getCookie('discount');
if (discountCookie != null && discountCookie.length > 1) {
document.getElementById('cart_form').action = '/cart?discount=' + discountCookie;
}
})();
STEP 3
//Insert this code in header.liquid (for reciving discount also in a product page), preferably at the bottom of the page inside script tag
//Also, make sure your chechout "<form>" has an ID of "checkoutgsdr".
/*Function to getcookie*/
function getCookie(nome) {
var name = nome + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ')
c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
(function() {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
var product = urlParams.get('discount');
if (product == null || product.length <= 1) {
var discountCookie = getCookie('discount');
if (discountCookie != null && discountCookie.length > 1) {
document.getElementById('checkoutgsdr').action = '/checkout?discount=' + discountCookie;
}
}else{
document.getElementById('checkoutgsdr').action = '/checkout?discount=' + product;
}
})();

Custom checkbox not working in Chrome and Safari browser

i used below code for custom checkbox,
HTML
<div class="agree">
<label for="agree_check" class="label_check"><input type="checkbox" class="agree_check" id="agree_check" />Agree</label>
</div>
CSS
.has-js .label_check { padding-left: 34px; }
.has-js .label_check { background: url(../images/box1.png) no-repeat; }
.has-js label.c_on { background: url(../images/box1-with-mark.png) no-repeat; }
.has-js .label_check input { position: absolute; left: -9999px; }
Script
<script type="text/javascript">
var d = document;
var safari = (navigator.userAgent.toLowerCase().indexOf('safari') != -1) ? true : false;
var gebtn = function(parEl,child) { return parEl.getElementsByTagName(child); };
onload = function() {
var body = gebtn(d,'body')[0];
body.className = body.className && body.className != '' ? body.className + ' has-js' : 'has-js';
if (!d.getElementById || !d.createTextNode) return;
var ls = gebtn(d,'label');
for (var i = 0; i < ls.length; i++) {
var l = ls[i];
if (l.className.indexOf('label_') == -1) continue;
var inp = gebtn(l,'input')[0];
if (l.className == 'label_check') {
l.className = (safari && inp.checked == true || inp.checked) ? 'label_check c_on' : 'label_check c_off';
l.onclick = check_it;
};
if (l.className == 'label_radio') {
l.className = (safari && inp.checked == true || inp.checked) ? 'label_radio r_on' : 'label_radio r_off';
l.onclick = turn_radio;
};
};
};
var check_it = function() {
var inp = gebtn(this,'input')[0];
if (this.className == 'label_check c_off' || (!safari && inp.checked)) {
this.className = 'label_check c_on';
if (safari) inp.click();
} else {
this.className = 'label_check c_off';
if (safari) inp.click();
};
};
var turn_radio = function() {
var inp = gebtn(this,'input')[0];
if (this.className == 'label_radio r_off' || inp.checked) {
var ls = gebtn(this.parentNode,'label');
for (var i = 0; i < ls.length; i++) {
var l = ls[i];
if (l.className.indexOf('label_radio') == -1) continue;
l.className = 'label_radio r_off';
};
this.className = 'label_radio r_on';
if (safari) inp.click();
} else {
this.className = 'label_radio r_off';
if (safari) inp.click();
};
};
</script>
now i need to check the checkbox is checked or not.. it is works in FF but not works in Chrome and Safari browser.
if (jQuery('#agree_check').is(':checked')) {
alert("checked");
}
else
{
alert("Not checked");
}
when i checked the checkbox it displays "checked" in FF.. but in Chrome and safari it displays "not checked".
what is the issue?
My solution, working also on server side - codebehind (runat="server" attribute for label and checkbox), consist to add checked/unchecked state for critical browser. Maybe this work for all browser, clearing if statement.
var check_it = function () {
var inp = gebtn(this, 'input')[0];
if (this.className == 'label_check c_off' || (!safari && inp.checked)) {
this.className = 'label_check c_on';
if (chrome) inp.checked = true;
if (safari) inp.click();
} else {
this.className = 'label_check c_off';
if (chrome) inp.checked = false;
if (safari) inp.click();
};
};
Finally i found answer for this, it is just check in another way to make that condition true,
if (jQuery('#agree_check').is(':checked') || (jQuery('div.agree label').hasClass('c_on'))) {
alert("checked");
}
else
{
alert("Not checked");
}
now it's works fine in all browsers.
Thanks,
Ravichandran

regex with urls

I check if a given url matches another one (which can have wildcards).
E.g. I have the following url:
john.doe.de/foo
I'd now like to check whether the url is valid or not, the user defines the string to check with, e.g:
*.doe.de/*
That works fine, but with the following it should NOT work but it gets accepted:
*.doe.de
Here the function i wrote till now, the urls are stored as firefox prefs and i the "checkedLocationsArray" containts all urls to be checked.
function checkURLS(index)
{
if(index >= 0)
{
var pos = getPos("URL-Mask");
var url = tables[index][pos];
if(url != null && url != "")
{
var urlnow = "";
if(redlist_pref.prefHasUserValue("table.1"))
{
var checkedLocationsArray = new Array();
for(i = 0; i < tables.length; i++)
{
checkedLocationsArray[i] = tables[i][pos];
}
for(i=0;i<checkedLocationsArray.length;i++)
{
urlnow = checkedLocationsArray[i];
if(urlnow == url)
{
return true;
}
if(urlnow.indexOf('*.') != -1)
{
while(urlnow.indexOf("*.") != -1)
urlnow = urlnow.replace("\*.", "\.[^\.]*");
}
if(urlnow.indexOf('.*') != -1)
{
while(urlnow.indexOf(".*") != -1)
urlnow = urlnow.replace(".\*", "([^\.]*\.)");
}
if(urlnow.indexOf('/*') != -1)
{
while(urlnow.indexOf("/*") != -1)
urlnow = urlnow.replace("/*", /\S\+*/)
}
else if(url.lastIndexOf('/') != -1)
{
return false;
}
var regex = new RegExp(urlnow);
var Erg = regex.exec(url);
if(Erg != null)
return true;
}
}
return false;
}
}
}
i think the "else if(url.indexOf('/') != -1)" is the important part. It should work just fine like that, if I alert it I even get that the result is true but it seems like the if is not being executed..
If anything is unclear, please just post a comment. Thanks in advance!
Why don't you just add the characters for beginning and end of string?
function checkURLS(index)
{
if(index >= 0)
{
var pos = getPos("URL-Mask");
var url = tables[index][pos];
if(url != null && url != "")
{
var urlnow = "";
if(redlist_pref.prefHasUserValue("table.1"))
{
var checkedLocationsArray = new Array();
for(i = 0; i < tables.length; i++)
{
checkedLocationsArray[i] = tables[i][pos];
}
for(i=0;i<checkedLocationsArray.length;i++)
{
urlnow = checkedLocationsArray[i];
if(urlnow == url)
{
return true;
}
//Check there's nothing else in the string
urlnow = '^' + urlnow + '$';
if(urlnow.indexOf('*') != -1)
{
while(urlnow.indexOf("*") != -1)
urlnow = urlnow.replace("\*", ".*");
}
else if(urlnow.lastIndexOf('/') != -1)
{
return false;
}
var regex = new RegExp(urlnow);
var Erg = regex.exec(url);
if(Erg != null)
return true;
}
}
return false;
}
}
}
The problem seems that you don't check for the start and the end of the string. Change your code to something like
urlnow = '^'+urlnow+'$'; // this is new
var regex = new RegExp(urlnow);
^ is the RegExp code for string-start and $ the code for string-end. That way you ensure that the whole url has to match the pattern and not only a part of it.
I figured out that I did the url was not the current url, I changed that below.
I also changed that the * are now replaced with a regular expression and the dots have to be there in this situation.
function redlist_checkURLS(index)
{
if(index >= 0)
{
var pos = getPos("URL-Mask");
var url = currenturl.replace("http://", "");
if(url != null && url != "")
{
var urlnow = "";
if(pref.prefHasUserValue("table.1"))
{
var urlsok = 0;
var checkedLocationsArray = new Array();
for(i = 0; i < tables.length; i++)
{
checkedLocationsArray[i] = tables[i][pos];
}
for(i=0;i<checkedLocationsArray.length;i++)
{
urlnow = checkedLocationsArray[i];
if(urlnow == url)
{
return true;
}
if(urlnow.indexOf('*') != -1)
{
while(urlnow.indexOf("*") != -1)
urlnow = urlnow.replace("*", "\\S+")
}
var regex = new RegExp(urlnow);
var Erg = regex.exec(url);
if(Erg != null && Erg == url)
return true;
}
}
return false;
}
}
}
Thanks for your help thought!

Mark unmark javascript?

I've got a function to select all checkboxes in a table:
<script type="text/javascript">
function checkAll() {
var tab = document.getElementById("logs");
var elems = tab.getElementsByTagName("input");
var len = elems.length;
for (var i = 0; i < len; i++) {
if (elems[i].type == "checkbox") {
elems[i].checked = true;
}
}
}
But I can't get it to uncheck them all if they are checked. How could I do that?
<th width='2%'>Mark</th>";
Also in javascript is it possible to rename "Mark" to "Un-Mark" if I execute checkAll()?
This should do both of the things u want:
function checkAll(obj) {
var tab = document.getElementById("logs");
var elems = tab.getElementsByTagName("input");
var len = elems.length;
for (var i = 0; i < len; i++) {
if (elems[i].type == "checkbox") {
if(elems[i].checked == true){
elems[i].checked = false;
}
else{
elems[i].checked = true;
}
}
}
if(obj.innerHTML == 'Mark') { obj.innerHTML = 'Unmark' }
else { obj.innerHTML = 'Mark' }
}
html:
<th width='2%'>Mark</th>";
1) why don't u use some js framework, like jQuery?
2) to remove checked, use elems[i].removeAttribute('checked') or set elems[i].checked = false;
3) to rename, you have to set it's innerHTML or innerText to Un-Mark
Add a little more logic to see if they're already checked. This will invert their current checked state.
for (var i = 0; i < len; i++) {
if (elems[i].type == "checkbox") {
if (!elems[i].checked) {
elems[i].checked = true;
}
else elems[i].checked = false;
}
}
If you just want to uncheck all, simply use:
elems[i].checked = false;
This will check them all regardless of their current state, or uncheck them all, depending on the current text of "Mark" or "Unmark".
<script type="text/javascript">
function checkAll(obj) {
var tab = document.getElementById("logs");
var elems = tab.getElementsByTagName("input");
var len = elems.length;
var state = obj.innerHTML == 'Mark';
for (var i = 0; i < len; i++) {
if (elems[i].type == "checkbox") {
elems[i].checked = state;
}
}
obj.innerHTML = state ? 'Mark' : 'Unmark';
}
And then the HTML changes to:
<th width='2%'>Mark</th>";
To uncheck, try:
elems[i].checked = false;
i sugest you use jquery, everything is easier.
with jquery you just have to do something like this (+/-):
$(function(){
$('a.ClassName').click(function(){
var oTbl = $('#tableID');
$('input[type="checkbox"]', oTbl).attr("checked", "checked")
});
})

Changing link color based on stylesheet function

I am a novice JavaScript programmer; any help would be greatly appreciated.
I have successfully implemented a script that allows users to switch from a "regular view" to a "high contrast view". The script is simply changing stylesheets.
I have also set up the script with a basic toggle: when a user clicks "High Contrast View" the link text changes to "Back".
However, I need to modify how the toggle works: rather than changing the link text, I need to change the link color.
I know that I can create a function with .style.color, but I am not sure how to integrate this in to my current script.
JavaScript:
function load_all() {
var cssval;
cssval = get_cookie("cssclass");
if (cssval == null || (cssval != "Normal CSS" && cssval != "High-Contrast-View")) {
cssval = "Normal CSS";
}
set_stylesheet(cssval);
}
function switchStyle(newtitle) {
set_stylesheet(newtitle);
finish_stylesheet();
}
function set_stylesheet(newtitle) {
var csslink;
if (newtitle == null) {
if (get_stylesheet() == "Normal CSS") newtitle = "High-Contrast-View";
else newtitle = "Normal CSS";
}
for (var i = 0; (csslink = document.getElementsByTagName("link")[i]); i++) {
if (csslink.getAttribute("rel").indexOf("style") != -1 && csslink.getAttribute("title")) {
csslink.disabled = true;
if (csslink.getAttribute("title") == newtitle)
csslink.disabled = false;
}
}
set_cookie("cssclass", newtitle, 28);
}
function finish_stylesheet() {
var nojsanchor, nojsspan, newtitle;
newtitle = get_stylesheet();
nojsanchor = document.getElementById("footer_nojslink");
nojsspan = document.getElementById("contrastToggle");
if (nojsanchor != null && nojsspan != null) {
while (nojsspan.hasChildNodes())
nojsspan.removeChild(nojsspan.childNodes[0]);
nojsspan.appendChild(document.createTextNode(newtitle == "Normal CSS" ? "high contrast" : "back"));
nojsanchor.href = "javascript:switchStyle('" + (newtitle == "Normal CSS" ? "High-Contrast-View" : "Normal CSS") + "')";
}
}
function get_stylesheet() {
var i, a;
for (i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled)
return a.getAttribute("title");
}
return null;
}
function accepts_cookies() {
document.cookie = "cookiecheck=true; path=/";
var cookies = document.cookie;
if (cookies.indexOf("cookiecheck") >= 0)
return true;
else
return false;
}
function set_cookie(name, value, days) {
var expire;
if (days > 0) {
expire = new Date();
expire.setDate(expire.getDate() + days);
}
else
expire = null;
document.cookie = name + "=" + escape(value) + (expire == null ? "" : ";expires=" + expire.toGMTString()) + ";path=/";
}
function get_cookie(name) {
var cookielist, cookie;
cookielist = document.cookie.split(";");
for (var i = 0; i < cookielist.length; i++) {
cookie = cookielist[i];
while (cookie.charAt(0) == " ")
cookie = cookie.substring(1);
if (cookie.indexOf(name + "=") == 0)
return unescape(cookie.substring(name.length + 1));
}
return null;
}
With your current code you should be able to do this:
document.getElementById("footer_nojslink").style.color = "#A6A6A6";
If you find yourself doing this kind of task frequently it's going to be worth your time to learn jQuery. It can sometimes make things simpler, and takes away most cross browser headaches. Here is a jQuery example for the specific example you are asking, changing link color;
$('#footer_nojslink').css('color','#A6A6A6');
easy
import the two (or more) stylesheets...
<head>
<link rel="stylesheet" href="style_1.css">
<link rel="stylesheet" href="style_2.css">
</head>
and then enable/disable them this way:
<script>
document.styleSheets[0].disabled=true;
document.styleSheets[1].enabled=true;
</script>
Now you can change the entire style of your site, not only the links.
https://developer.mozilla.org/En/DOM/Document.styleSheets

Categories

Resources