Store CSS or HTML in localStorage - javascript

I have this function to toggle a dark mode on and of with a single button.
It checks if the dark.css stylesheet is already added to the site, if yes it removes it. If there isn't a dark.css it loads it and appends it to the head.
Now I want to store this information in the localStorage so the browser remembers whether the dark.css should be loaded or not.
$(function() {
$('#toggler').click(function(){
if ($('link[href*="css/dark.css"]').length) {
$('link[href*="css/dark.css"]').remove();
}
else {
var lightMode = document.createElement('link');
darkMode.rel="stylesheet";
darkMode.href="css/dark.css";
document.getElementsByTagName('head')[0].appendChild(darkMode);
}
});
})

All you have to do is check localStorage in your jQuery function. Preferably earlier in the function (so DOM is updated quickly in case you have some intensive code elsewhere), though not required.
$( function () {
function appendDarkMode() {
var darkMode = document.createElement( 'link' );
darkMode.rel = 'stylesheet';
darkMode.href = 'css/dark.css';
document.getElementsByTagName( 'head' )[ 0 ].appendChild( darkMode );
}
// This is run when page is first loaded.
if ( localStorage ) {
var useDarkMode = localStorage.getItem( 'useDarkMode' );
// The boolean we set in the click handler will become a string.
useDarkMode === 'true' ? appendDarkMode() : localStorage.setItem( 'useDarkMode', false );
}
// Theme click handler.
$( '.toggler' ).on( 'click', function ( e ) {
var $darkModeLink = $( 'link[href*="css/dark.css"]' );
$darkModeLink.length ? $darkModeLink.remove() : appendDarkMode();
if ( localStorage ) {
// Note that we're inverting the value here. By the time this
// is run, we will have changed whether or not `dark.css` is
// on the page. Which is opposite the initial value of
// `$darkModeLink`.
localStorage.setItem( 'useDarkMode', !$darkModeLink.length );
}
} );
} );

Although I don't think your approach is the best (loading this way could produce a 'flash' of improperly styled content depending on where you put your JS logic), here's my solution (not tested, but should work):
FYI: You'll want to check for localStorage availability or roll a pollyfill. See Mozilla Docs
$(function() {
var themes = {
light: 'light',
dark: 'dark'
};
var currentTheme = themes.light; // default to light
function changeTheme(theme) {
if (!theme || !themes[theme]) return;
setTheme(theme);
Object.keys(themes).forEach(function(t) {
var linkEl = $('link[href*="css/' + t + '.css"]');
if (linkEl.length && t !== theme) {
linkEl.remove();
}
});
}
function setTheme(theme) {
if (!theme || !themes[theme]) return;
var linkEl = document.createElement('link');
linkEl.rel="stylesheet";
linkEl.href="css/" + theme + ".css";
document.getElementsByTagName('head')[0].appendChild(linkEl);
if (localStorage) {
localStorage.setItem('theme', theme);
}
currentTheme = theme;
}
if (localStorage) {
var theme = localStorage.getItem('theme');
changeTheme(theme);
} else {
changeTheme(currentTheme);
}
$('#toggler').click(function(){
switch (currentTheme) {
case themes.light:
changeTheme(themes.dark);
break;
case themes.dark:
default:
changeTheme(themes.light);
break;
}
});
})

Related

JS dark theme not changing

I'm trying to make light/light theme for a table in my project,its dark by default so i'm trying to change it to light when i click on the button but when i click it changes to light but not turning back any hints ?
var element = document.getElementById('toggleTheme')
var attributeContent = element.getAttribute('data-layout-mode')
let toggleTheme = document.querySelector(".light-dark-mode");
let styleSheet = document.querySelector("#color-theme");
console.log(attributeContent);
if (attributeContent=="dark") {
toggleTheme.addEventListener("click", () => {
styleSheet.setAttribute("href", "")
})
} else if (attributeContent=="light") {
toggleTheme.addEventListener("click", () => {
styleSheet.setAttribute("href", "{{ asset('css/style.css') }}")
})
} else {
console.log("not found")
}
You only define what to toggle based on the initial value of the attributeContent.
You should better do the test, on whether it is currently dark or light, each time the toggle is clicked.
something like
var element = document.getElementById('toggleTheme')
let toggleTheme = document.querySelector(".light-dark-mode");
let styleSheet = document.querySelector("#color-theme");
toggleTheme.addEventListener("click", function() {
// read the layout mode
var attributeContent = element.getAttribute('data-layout-mode');
if (attributeContent == "dark") {
styleSheet.setAttribute("href", "");
// set the layout mode to the new value
element.setAttribute('data-layout-mode', 'light');
} else if (attributeConten == "light") {
styleSheet.setAttribute("href", "{{ asset('css/style.css') }}");
// set the layout mode to the new value
element.setAttribute('data-layout-mode', 'dark');
} else {
console.log("not found")
}
})

JS script dynamic loading inconsitent

I need help on getting some dynamic js loading working properly. the issue I'm having now is that it is not consistently loading the js script when loading the page. here is the script that I have at the bottom of the page that I'm opening:
function getJSOnload() {
var element;
var parent = document.body;
var cdn = [
LoadFormValidationScript(LoginFormValidator),
LoadFormValidationScript(SetFormLocaleLang)
];
var i = 0, file;
for (i;i<cdn.length;i++) {
file = cdn[i];
element = document.createElement("script");
element.type = "text/javascript";
element.src = file;
parent.appendChild(element);
//free file's value
file = null;
}
};
if (window.addEventListener) {
window.addEventListener("load", getJSOnload(), false);
}
else if (window.attachEvent) {
window.attachEvent("onload", getJSOnload());
}
else window.onload = getJSOnload();
this is the LoadFormValidationScript that i have in an external js file
function LoadFormValidationScript(callback){
function LoadValidationScripts() {
$.getScript('/plugins/script1.min.js', function() {
$.getScript('/plugins/script2.min.js', function() {
$.getScript('/plugins/script3.addons.min.js', function() {
$.getScript('/plugins/script.es_ES.js', function() {
$.getScript('/plugins/script4.fr_FR.js', function() {
$.getScript('/plugins/script5.de_DE.js', callback);
});
});
});
});
});
}
if (!$.fn.formValidation){
LoadValidationScripts();
} else {
if (callback && typeof(callback) === "function") {
callback();
}
}
}
and this is the "setFormLocaleLang" function as an example since it is short one
function SetFormLocaleLang(){
var nberOfForm = document.forms.length; //get number of forms on the page
// if there are no forms in the page don't waist your time
if (nberOfForm > 0) {
var Locale = "en_US"; //default formVlaidation language
//var lang = $('html').attr('lang'); // get the page language
var lang = $("#selectedLanguage").attr('data-lang-id');
// assign the Locale depending on page language
switch (lang) {
case "en" : Locale = 'en_US'; break;
case "fr" : Locale = 'fr_FR'; break;
case "es" : Locale = 'es_ES'; break;
case "de" : Locale = 'de_DE'; break;
default : break;
};
//set the locale for all the forms in the page
for (var i = 0; i < nberOfForm; i++) {
var strFormID = "#" + document.forms[i].id;
$(strFormID).formValidation('setLocale', Locale);
}
}
}
like is said it does work and load the scripts but not all the time, sometimes i have to refresh the page like 3 time for the script to load and sometimes it loads on the first try as soon as i open the page. not sure what is going on and why i get this behaviour.
You're attaching the handlers incorrectly - you're calling getJSOnload() immediately, instead of waiting for document-loaded, as you intend. Reference, don't call, the function:
if (window.addEventListener) {
window.addEventListener("load", getJSOnload, false);
}
else if (window.attachEvent) {
window.attachEvent("onload", getJSOnload);
}
else window.onload = getJSOnload;

How to retrieve the ajax data whose loading requires a mouse click with PhantomJS or other tools

I'm using PhantomJS to retrieve this page: Target Page Link. The contents I need are under the "行政公告" and "就業徵才公告" tabs. Because this page is written in Chinese, in case you cannot find the tabs, you can use "find" function of the browsers to find the "行政公告" and "就業徵才公告" tabs. Because the contents under the "行政公告" tab are the loaded as the default option, I can easily use the script below to retrieve the page:
var page = require('webpage').create();
var url = 'http://sa.ttu.edu.tw/bin/home.php';
page.open(url, function (status) {
var js = page.evaluate(function () {
return document;
});
console.log(js.all[0].outerHTML);
phantom.exit();
});
But the contents under the "就業徵才公告" tab are not loaded after I use the PhamtomJS to emulate the mouse click with the code below:
var page = require('webpage').create();
var url = 'http://sa.ttu.edu.tw/bin/home.php';
page.open(url, function (status) {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
// jQuery is loaded, now manipulate the DOM
$('#sm_adf63b93c89375a0bade42e5360b73274_1_Dyn_2_1').trigger('mouseover');
});
var js = page.evaluate(function () {
return document;
});
console.log(js.all[0].outerHTML);
phantom.exit();
});
This doesn't work as the contents under the "就業徵才公告" tab are not loaded. How should I do to retrieve the contents under the "就業徵才公告" tab?
Update:
After read a PhantomJS example, I refactored the code to below. It didn't work because the contents under the "就業徵才公告" tab are not loaded.
var page = require('webpage').create();
var address = 'http://sa.ttu.edu.tw/bin/home.php';
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit();
} else {
window.setTimeout(function () {
var results = page.evaluate(function() {
$('#sm_adf63b93c89375a0bade42e5360b73274_1_Dyn_2_1').trigger('mouseover');
return document.documentElement.innerHTML;
});
console.log(results);
phantom.exit();
}, 5000);
}
});
If any way could solve this problem is welcomed. Not limited to PhamtoJS.
Tested this code, and it outputs the correct image with the desired tab selected. It wasn't so straightforward because of the underlying structure of the page. Hopefully you can use this as a bit of a learning exercise in processing the DOM.
// utility function to send mouseclick event to an element
function mouseclick( element ) {
// create a mouse click event
var event = document.createEvent( 'MouseEvents' );
event.initMouseEvent( 'click', true, true, window, 1, 0, 0 );
// send click to element
element.dispatchEvent( event );
}
// final function called, output screenshot, exit
function after_clicked( page ) {
console.log( "+after_clicked()" );
page.render( "after_click.png" );
console.log( "Done" );
phantom.exit( 0 );
}
// middle function, click on desired tab
function click_div( page ) {
console.log( "+click_div()" );
var clicked = page.evaluate(
function ( mouseclick_fn ) {
// want the div with class "submenu"
var div = document.querySelector( "div.submenu" );
if ( ! div ) {
return false;
}
// want all the list elements in the div
var li_array = div.querySelectorAll( "li" );
if ( ! li_array ) {
return false;
}
// we want the 2nd list element
var li2 = li_array[1];
if ( ! li2 ) {
return false;
}
// want the anchor inside the 2nd list element
var anchor = li2.querySelector( "a" );
if ( ! anchor ) {
return false;
}
// must focus on anchor to trigger underlying javascript on page
anchor.focus();
// want the div within this anchor, so we can click on the div
var element = anchor.querySelector( "div" );
if ( ! element ) {
return false;
}
// click on this inner div
mouseclick_fn( element );
return true;
}, mouseclick
);
if ( ! clicked ) {
console.log( "Failed to find desired element" );
phantom.exit( 1 );
return;
}
console.log( "- clicked, waiting 5 seconds" );
window.setTimeout(
function () {
after_clicked( page );
},
5000
);
}
// first function, create page, load page
function main() {
console.log( "+main()" );
var page = require('webpage').create();
page.open(
"http://sa.ttu.edu.tw/bin/home.php",
function (status) {
if ( status !== 'success' ) {
console.log( "Failed" );
phantom.exit( 1 );
return;
}
console.log( "- page loaded, waiting 2 seconds..." );
window.setTimeout(
function () {
click_div( page );
},
2000
);
}
);
}
main();

Why is my javascript preventing the browser from going to a link

I have a script on http://joelglovier.com to add a class of "active" to each navigation element when it's corresponding section in the document. The script is adapted with permission from w3fools.com, so it was written without my scenario in mind.
The difference is that on w3fools.com, the nav links only refer to elements on the page, whereas in my navigation, there is one element at the end that refers to a new page.
The problem is that as I have adapted it, it works fine for the links that refer to sections on the page. However, for some reason unbeknownst to me (sorry - JS/jQuery novice) it is blocking the browser from following the link to the new page (the Blog link).
I tried reading through the code and understanding what the script is doing - however I cannot seem to understand why it is blocking that external link from being clicked, or more specifically how to fix it.
Can anybody suggest the simplest way to remedy my issue without breaking the original functionality of the script for it's purpose?
See it live here: http://joelglovier.com
Or...
Markup:
<div id="site-nav">
<div class="wrap">
<nav id="nav-links">
Top
Background
Projects
Random
Credits
Blog <span class="icon"></span>
</nav>
</div>
Javascript:
(function($) {
$(function() {
var $nav = $('#nav-links'),
$navLinks = $nav.find('a.scroll'),
cache = {};
$docEl = $( document.documentElement ),
$body = $( document.body ),
$window = $( window ),
$scrollable = $body; // default scrollable thingy, which'll be body or docEl (html)
// find out what the hell to scroll ( html or body )
// its like we can already tell - spooky
if ( $docEl.scrollTop() ) {
$scrollable = $docEl;
} else {
var bodyST = $body.scrollTop();
// if scrolling the body doesn't do anything
if ( $body.scrollTop( bodyST + 1 ).scrollTop() == bodyST) {
$scrollable = $docEl;
} else {
// we actually scrolled, so, er, undo it
$body.scrollTop( bodyST - 1 );
}
}
// build cache
$navLinks.each(function(i,v) {
var href = $( this ).attr( 'href' ),
$target = $( href );
if ( $target.length ) {
cache[ this.href ] = { link: $(v), target: $target };
}
});
// handle nav links
$nav.delegate( 'a', 'click', function(e) {
// alert( $scrollable.scrollTop() );
e.preventDefault(); // if you expected return false, *sigh*
if ( cache[ this.href ] && cache[ this.href ].target ) {
$scrollable.animate( { scrollTop: cache[ this.href ].target.position().top }, 600, 'swing' );
}
});
// auto highlight nav links depending on doc position
var deferred = false,
timeout = false, // so gonna clear this later, you have NO idea
last = false, // makes sure the previous link gets un-activated
check = function() {
var scroll = $scrollable.scrollTop(),
height = $body.height(),
tolerance = $window.height() * ( scroll / height );
$.each( cache, function( i, v ) {
// if we're past the link's section, activate it
if ( scroll + tolerance > v.target.position().top ) {
last && last.removeClass('active');
last = v.link.addClass('active');
} else {
v.link.removeClass('active');
return false; // get outta this $.each
}
});
// all done
clearTimeout( timeout );
deferred = false;
};
// work on scroll, but debounced
var $document = $(document).scroll( function() {
// timeout hasn't been created yet
if ( !deferred ) {
timeout = setTimeout( check , 250 ); // defer this stuff
deferred = true;
}
});
// fix any possible failed scroll events and fix the nav automatically
(function() {
$document.scroll();
setTimeout( arguments.callee, 1500 );
})();
});
})(jQuery);
You're trying to tell it to scroll to "http://..." which doesn't exist on the current page, so it fails and does nothing.
It should work if you change your code to this
// handle nav links
$nav.delegate( 'a', 'click', function(e) {
// alert( $scrollable.scrollTop() );
e.preventDefault(); // if you expected return false, *sigh*
if ( cache[ this.href ] && cache[ this.href ].target ) {
// preserve http:// links
if (this.href.substr(0, "http://".length) == 'http://')
location.href = this.href;
else
$scrollable.animate( { scrollTop: cache[ this.href ].target.position().top }, 600, 'swing' );
}
});

Why is the title and favicon of the window/tab not updating?

I'm playing around with jetpack to change the title (and ideally the favicon) of certain pages.
Firebug is showing that the HTML of the page has been changed correctly but Firefox just won't update the title of the window and/or tab.
This has to be possible, somehow, since Twitter Search is doing exactly that. It's updating the title as more search results show up, isn't it?
I guess I'm just missing something... any idea?
Example code as suggested in the comment:
function replaceTitle(doc)
{
if (doc.location.protocol == "http:" || doc.location.protocol == "https:")
{
var host=doc.location.host;
if(host.indexOf("stackoverflow.com")>=0)
{
var title=doc.getElementsByTagName("title")
console.log(title);
if(title)
{
var val=title[0];
if(val)
{
console.log("val", val);
console.log("valx", val.textContent);
val.textContent="Foo";
console.log("valz", val.textContent);
}
}
}
}
}
var state = "on";
function toggleState()
{
if( state == "off" )
{
jetpack.tabs.onReady(replaceTitle);
state = "on";
}
else
{
jetpack.tabs.onReady.unbind(replaceTitle);
state = "off";
}
console.log(state);
// This is a temporary way of keeping all browser window states
// in sync. We are working on a better API for this.
/*
widgets.forEach(function(widget) {
widget.defaultView.wrappedJSObject.setState(state);
});
*/
}
jetpack.statusBar.append(
{
html: "Boo",
onReady: function(widget)
{
console.log("ready");
// This is a temporary way of keeping all browser window states
// in sync. We are working on a better API for this.
/*
widgets.push(widget);
widget.defaultView.wrappedJSObject.setState(state);
*/
$(widget).click(toggleState);
},
onUnload: function(widget)
{
console.log("unload");
/*
widgets.splice(widgets.indexOf(widget), 1);
*/
},
width: 42
});
console.log("Test");
Irritatingly, it doesn't even show logs anymore since jetpack and firebug have been updated in the meantime :p
I'd expect this code to replace the title of stackoverflow.com pages with "Foo" - but this is just an example, replace stackoverflow.com with anything else if that might help, i.e. probably a site with less javascript magic than SO.com.
Update:
I solved the problem with the help of the answer below.
The working example looks like this:
function replaceTitle()
{
var doc=this.contentDocument;
console.log("replaceTitle "+ doc);
if(doc)
{
var location = doc.location;
if ( (location.protocol == "http:" || location.protocol == "https:")
&& location.host.indexOf("stackoverflow.com") !== -1 )
{
doc.title = "Foo";
console.log("Title set to "+doc.title);
}
else
{
console.log("Location "+location);
}
}
}
var state = "on";
function toggleState()
{
if( state == "off" )
{
state = "on";
jetpack.tabs.onReady(replaceTitle);
}
else
{
state = "off";
jetpack.tabs.onReady.unbind(replaceTitle);
}
console.log(state);
}
jetpack.statusBar.append(
{
html: "Boo",
onReady: function(widget)
{
console.log("ready: "+state);
$(widget).click(toggleState);
},
onUnload: function(widget)
{
console.log("unload");
},
width: 42
});
console.log("Testing");
might want to try
function replaceTitle(doc)
{
var location = doc.location;
if ( (location.protocol == "http:" || location.protocol == "https:")
&& location.host.indexOf("stackoverflow.com") !== -1 ) {
document.title = "Foo";
}
}
works for me
http://pastebin.me/4a3550e0dbe19?framepage
if you back down to firebug 1.4.0b4 it will fix that console problem you're having.
http://groups.google.com/group/mozilla-labs-jetpack/browse_thread/thread/c0cba73c67f19530#

Categories