Saving User-Chosen Stylesheet via jQuery and Cookies - javascript

Edit: I figured it out. I'm a complete numpty and didn't test putting the switcher code at the top of my other scripts. As soon as I did that, I fixed it, and it works perfectly.
Old post below.
I want to be able to have my users select a stylesheet via button or link, and have the browser remember that. I'm not great with jQuery, but I know generally enough to follow tutorials and reverse-engineer, to a point.
I have been attempting to use this plugin, but it's not playing nicely with my existing code. There are a couple of things that could be causing the issue, but I think the most likely culprit is the different versions of jQuery that are used. Using just the 1.4.4 breaks some of the core functionality (the ability to reset the checkbox state), and using just the 1.11.2 means that the plugin doesn't work at all. I've no idea how to resolve this, nor even what to google.
After further testing, when using the demo's index.html, I can use just the 1.11 library without breaking functionality. But when using my index.html, it doesn't function at all. So that's probably not the issue.
The demo HTML is viewable online, and here is a pastebin of my full index.html. Obligatory plea for mercy regarding my subpar coding skills.
Here's the demo header:
<link type="text/css" rel="stylesheet" href="css/styles.css" />
<link type="text/css" rel="stylesheet" id="theme" href="css/theme1.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js?ver=1.4.4"> </script>
<script type="text/javascript" src="js/jquery.style-switcher.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#header').styleSwitcher();
});
</script>
And here's my header:
<link href="css/style.css" rel="stylesheet" type="text/css">
<link href="css/classic.css" rel="stylesheet" type="text/css">
<script src="http://code.jquery.com/jquery-1.11.2.min.js" type="text/javascript"></script>
<link href='http://fonts.googleapis.com/css?family=Marcellus+SC|Open+Sans' rel='stylesheet' type='text/css'>
<link rel="icon" type="image/png" href="http://starbuckguild.com/ore/favicon.png">
<script>
//Add functionality for hiding perm nodes that may be silver or iron
$(document).ready(function () {
$("input[name=both]").not(".textbox").click(function () {
if ($(this).is(":checked")) {
$("input[name=both]").prop('checked', true)
$("input[name=both]").parent(".container").addClass("visited_node");
$("input[name=both]").parent(".container").hide(500);
}
else $(this).parent(".container").removeClass("visited_node")
});
$("input[name=both2]").not(".textbox").click(function () {
if ($(this).is(":checked")) {
$("input[name=both2]").prop('checked', true)
$("input[name=both2]").parent(".container").addClass("visited_node");
$("input[name=both2]").parent(".container").hide(500);
}
else $(this).parent(".container").removeClass("visited_node")
});
$("input[name=both3]").not(".textbox").click(function () {
if ($(this).is(":checked")) {
$("input[name=both3]").prop('checked', true)
$("input[name=both3]").parent(".container").addClass("visited_node");
$("input[name=both3]").parent(".container").hide(500);
}
else $(this).parent(".container").removeClass("visited_node")
});
//Mark node as visited.
$("input").not(".textbox").click(function () {
if ($(this).is(":checked")) {
$(this).parent(".container").addClass("visited_node");
$(this).parent(".container").hide(500);
}
else $(this).parent(".container").removeClass("visited_node")
});
//Show visited nodes
$("#showall").click(function () {
$(".visited_node").show();
});
//Hide visited nodes
$("#hideall").click(function () {
$(".visited_node").hide();
});
//Hide all nodes with list price less than 1s
$("#good").click(function () {
$("input[name=bad]").parent(".container").addClass("visited_node");
$("input[name=bad]").parent(".container").hide();
});
//Add short route function
$("#short").click(function () {
$("input").parent(".container").addClass("visited_node");
$("input").parent(".container").hide();
$("input[name=1hr]").parent(".container").removeClass("visited_node");
$("input[name=1hr]").parent(".container").show();
});
//Prompt user to reset all nodes
$("#uncheckall").click(function () {
$(".button").show();
$(this).hide();
});
//Actually reset all nodes if user is sure
$("#imsure").click(function () {
$(".visited_node").show();
$("input").not(".textbox").prop("checked", false);
$(".visited_node").removeClass("visited_node");
$(".button").show();
$(this).hide();
});
//Hide or show nodes by type
$("#nav a").click(function () {
var id = $(this).attr('id');
id = id.split('_');
if ($(this).is(".off")){
$("#menu #menu_" + id[1]).show();
}
else {
$("#menu #menu_" + id[1]).hide();
}
$(this).toggleClass("off");
});
//Show map to nodes when clicked
var option = 'blank';
var url = window.location.href;
option = url.match(/option=(.*)/)[1];
showDiv(option);
});
function showDiv(option) {
$('.boxes').hide();
$('#' + option).show();
$('#blank').hide();
}
The plugin also requires
<div id="header">
Default
Darkness
Colorful
</div>
to be placed in the body of the page. I've just been putting it inside my navigation div at the top of the page, but perhaps I'm making a mistake there as well/instead.
As an aside, I note that the local machine version of the demo's index.html does not save the stylesheet preferences, whereas the web version does - I assume this is normal behaviour? Edit: It is. It works fine when uploaded.

Related

After refreshing a button, text is changing in jquery

When I click a button the text will change every time. For example when I go to the page it shows 'Close'. If I click that button and it's value will change to 'Open'. It happens in another way also. If I click the 'Open' then it changes to close.
However the problem is if the button is in 'Open' state and if I do refresh it's changing to 'Close'. But if it's in 'Close' and I click refresh it's not changing to 'Open'.
What I need is after every click it should change from open to close or close to open. But after refresh also it should be in the same state. it should not get changed. How should I do it.
function changeStatus() {
console.log("Hi");
var val = document.getElementById("openClose").value;
$.ajax({
type: 'POST',
url: '/change/me',
data: {
'val': val
},
success: function(result) {
alert("The text has been changed");
}
})
}
$(".changeme").click(function() {
$(this).text(function(i, text) {
return text === 'Close' ? 'Open' : 'Close'
})
})
<!--Stylesheets-->
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" />
<!--JS files-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<button class="btn btn-danger changeme" onclick="changeStatus()" id="openClose">Close</button>
</div>
Version with local storage (but you can't test it inside snippet, snippet don't give acces to local storage, but codepen does) Demo on codepen
let store = window.localStorage
function changeStatus() {
let val
store.getItem('btnstat') === "Open"? checkUpdLocal("Close") : checkUpdLocal("Open") // toggle status
val = store.getItem('btnstat')
$.ajax({
type: 'POST',
url: '/change/me',
data: {
'val': val
},
success: function(result) {
alert("The text has been changed");
}
})
}
function checkUpdLocal(stat){
if(!store.getItem('btnstat')){ // if local storage does not exist
store.setItem('btnstat', "Close") // close by default
}else if(store.getItem('btnstat') && !stat){ // if storage exist but we don't change status (first ini) - change buttno text
$('.changeme').html(store.getItem('btnstat'))
}
if(stat){ // setter
store.setItem('btnstat', stat)
$('.changeme').html(stat)
}else{
return store.getItem('btnstat') // getter
}
}
$( document ).ready( function(){checkUpdLocal()})
<!--Stylesheets-->
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" />
<!--JS files-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<button class="btn btn-danger changeme" onclick="changeStatus()" id="openClose">Close</button>
</div>
Here is an example of using sessionStorage to persist state temporarily.
The sessionStorage object stores data for only one session (the data
is deleted when the browser tab is closed). sessionStorage will not
work on old browsers that do not have support for it.
<script type="text/javascript">
$(document).ready(function () {
if (sessionStorage.getItem("changeState") == null) {
$(".changeme").text("Close");
sessionStorage.setItem("changeState", "Close");
} else {
if (sessionStorage.getItem("changeState") === "Close") {
$(".changeme").text("Close");
} else {
$(".changeme").text("Open");
}
}
$(".changeme").click(function () {
if (sessionStorage.getItem("changeState") === "Close") {
$(this).text("Open");
sessionStorage.setItem("changeState", "Open");
} else {
$(this).text("Close");
sessionStorage.setItem("changeState", "Close");
}
})
});
</script>
When you use localStorage, you have to check if the value has been saved before
$( document ).ready(function(){
if(localStorage.getItem("openClose")!==undefined){
$('.changme').text(localStorage.getItem("openClose"));
});
(edited to put the lookup in ready function)
It's the older way, but you could also save the state in a cookie.
Save it with:
document.cookie = "Open";
on page load, retrieve it with
`
var state = document.cookie;
This is very awkward though; I would recommend using a cookie library to manipulate these.
Just one more answer if someone is thinking what if cookies are disabled in the browser and you still want to save the state of the elements on your web page according to the user's interaction.
In this case, you can save the state of the elements by doing AJAX call and save states to the database when the user changes the state of elements. But this would be a good approach only if you have lots of elements state to be saved. For 1-2 elements don't try this method. It will be inefficient.
By using cookies approach:
of course, you can store the 'state' in a cookie, and then retrieve that cookie when the page gets refreshed.
As cookies only admit strings, you can convert javascript objects to strings using
var str = JSON.stringify(obj);
and to convert back use
var obj = JSON.parse(str);
(JSON functions are supported in modern browsers).
This way you can save/retrieve a javascript object, you could store (in your case) some coordinates, positions, sizes, whatever you need.

Dynamically switching between bootstrap.css theme's

I am trying to switch between a dark & light theme I have created on my MVC application.
My _Layout.cshtml page loads the default theme I have created below
<link id="theme" rel="stylesheet" href="~/lib/bootstrap/dist/css/Original.css">
I have created the below buttons to switch between the themes below
<button id="light">Light</button><br />
<button id="dark">Dark</button>
My two other bootstrap themes are located in lib > bootstrap> dist > css >
I have the below js in my botstrap.js file
$('#dark').click(function () {
$('link[href="~/lib/bootstrap/dist/css/Dark.css"]').attr('href', '~/lib/bootstrap/dist/css/Dark.css');
});
$('#light').click(function () {
$('link[href="~/lib/bootstrap/dist/css/Dark.css"]').attr('href', '~/lib/bootstrap/dist/css/Light.css');
});
Not sure if I am making some obvious error but any help on this is appreciated.
Here it is in VanillaJS, check also if the href on the link tag resolves to CSS File correctly.
const darkBtn = document.querySelector('#dark');
const lightBtn = document.querySelector('#light');
const linkTag = document.querySelector('#theme');
darkBtn.addEventListener('click', () => {
linkTag.setAttribute('href', '~/lib/bootstrap/dist/css/Dark.css')
});
lightBtn.addEventListener('click', () => {
linkTag.setAttribute('href', '~/lib/bootstrap/dist/css/Light.css')
});
You probably need following code:
$('#dark').click(function () {
$('#theme').attr('href', '~/lib/bootstrap/dist/css/Dark.css');
});
$('#light').click(function () {
$('#theme').attr('href', '~/lib/bootstrap/dist/css/Light.css');
});
Your code is looking for a link-element where the href literally starts with ~/. In your razor page the href starts with this string. But ASP.NET replaces this with the path for the content-root, so for the browser, the href does not start with this string.
I downloaded Pieterjan solution and it began to work after I added event.preventDefault() like that:
$(document).ready(function () {
$('#dark').click(function () {
event.preventDefault();
$('#dynamicCss').attr('href', '/css/site-dark.css');
});
$('#light').click(function () {
event.preventDefault();
$('#dynamicCss').attr('href', '/css/site-light.css');
});
});
But website displays light theme again after refreshing the page.

Summernote v0.7.0 on change callback issue

Having a simple set up for summernote.
<div id="summernote">data-here</div>
$('#summernote').summernote({
height: 200, // set editor height
focus: true,
callbacks // any callbacks didn't worked, onChange, onBlur etc..(any tip on how to add proper callbacks here)
});
I tried to make jquery code to catch on change event of my summernote, like:
$('#summernote').on("summernote.change", function (e) {
# Problem here when deleting (keyboard backspace, calls twice)
-some code here-
}
My problem with the summernote.change is that when deleting text/content using keybord's backspace, the callback (on change) triggers twice instead.
Thus my inside function runs twice too.
Any idea on this guys, Thanks in advance.
I tried to recreate the issue. But it works fine for me.
$(document).ready(function() {
$('#summernote').summernote({
height: 200, // set editor height
focus: true,
callbacks: {
onInit: function() {
console.log('Summernote is launched');
},
onChange: function(contents, $editable) {
console.log('onChange:', contents, $editable);
}
}
});
$('#summernote').on('summernote.change', function(we, contents, $editable) {
console.log('summernote.change', contents, $editable);
});
});
<!-- include libraries(jQuery, bootstrap) -->
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>
<!-- include summernote css/js -->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.11/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.11/summernote.js"></script>
<div id="summernote">data-here</div>
Note: You should use either of the events onChange in callbacks or summernote.change not both.
As I know, it’s a known issue (https://github.com/summernote/summernote/issues/2888), but nobody tried to fix it.
So, I use it like this :
var mySec = 100;
var myEvent;
$('#summernote').on("summernote.change", function (e) {
clearTimeout(myEvent);
myEvent = setTimeout(function(){
console.log(e) // do something!
}, mySec);
});
I hope this will help you :)

Uncaught TypeError: $(...).tooltip is not a function

I have a project based in Spring Web model-view-controller (MVC) framework. The version of the Spring Web model-view-controller (MVC) framework is 3.2.8 deployed on a WebLogic Server Version: 12.1.2.0.0
I have this error loading 1 JSP
Uncaught TypeError: $(...).tooltip is not a function
This is everything I load and I checked 1 by 1 and all of them are loaded
<link href="/tdk/styles/bootstrap.css" type="text/css" rel="stylesheet">
<link href="/tdk/styles/admin.css" type="text/css" rel="stylesheet">
<link href="/tdk/styles/jquery.dataTables.css" type="text/css" rel="stylesheet">
<link href="/tdk/styles/dataTables.bootstrap.css" type="text/css" rel="stylesheet">
<link href="/tdk/styles/slides.css" type="text/css" rel="stylesheet">
<script src="/tdk/scripts/jquery.min.js" type="text/javascript"></script>
<script src="/tdk/scripts/bootstrap.js" type="text/javascript"></script>
<script src="/tdk/scripts/jquery.dataTables.js" type="text/javascript"></script>
<script src="/tdk/scripts/dataTables.bootstrap.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('[data-toggle="tooltip"]').tooltip();
var selected = [];
var table = $('#example').DataTable({
"dom": '<"top">rt<"bottom"lp><"clear">',
"autoWidth": false,
"paging": false,
"scrollX": false,
"scrollY": 300,
"scrollCollapse": true,
"rowCallback": function(row, data) {
if ($.inArray(data.DT_RowId, selected) !== -1) {
$(row).addClass('selected');
}
},
"columnDefs": [{
"targets": 'nosort',
"orderable": false
}, ]
});
$('#example tbody').on('click', 'input', function() {
$(this).closest("tr").toggleClass('selected');
if ($(this).is(':checked')) {
var theNameOfSelectedProduct = $(this).closest("tr").find("td.productname").text();
$('#selecteddevices').val($('#selecteddevices').val() + " " + theNameOfSelectedProduct);
$('#actions4devices button').removeAttr("disabled");
} else {
var theNameOfSelectedProduct = $(this).closest("tr").find("td.productname").text();
$('#selecteddevices').val($('#selecteddevices').val().replace(theNameOfSelectedProduct, ""));
if ($('#selecteddevices').val().trim().length == 0) {
$('#actions4devices button').not('.pull-right').attr("disabled", "disabled");
}
}
});
$('#refusedevicesButtonId').on('click', function() {
$('#theRefuseFile').show();
});
});
</script>
Can we see where you're using $.tooltip() ? It's possible that it occurs somewhere before the jQuery UI embed line. So try re-arranging your script includes so jQuery is first, jQuery UI is second, then along through the rest.
<script src="/tdk/scripts/jquery.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="/tdk/scripts/bootstrap.js" type="text/javascript"></script>
<script src="/tdk/scripts/jquery.dataTables.js" type="text/javascript"></script>
<script src="/tdk/scripts/dataTables.bootstrap.js" type="text/javascript"></script>
Hard to know without seeing your full code and knowing which files contains your calls to $.toolTip().
One other quick attempt would be to substitute jQuery for $ where you're using, i.e.:
$(".tips").toolTip()
would become:
jQuery(".tips").toolTip()
Be aware that jquery-ui has its own .tooltip() function and Bootstrap does too.
Try to reorder your js files like
<script src="/tdk/scripts/jquery.min.js" type="text/javascript"></script>
<!-- Jquery - ui right after-->
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="/tdk/scripts/bootstrap.js" type="text/javascript"></script>
<script src="/tdk/scripts/jquery.dataTables.js" type="text/javascript"></script>
<script src="/tdk/scripts/dataTables.bootstrap.js" type="text/javascript"></script>
It's probably due to the version of jQuery. At least it was me and I solved this problem like this. I was using jQuery 3.3.1. The problem was solved when I changed the django to 1.10.3. Add this,
http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js
It needs work.
tooltip() was only added to jQuery UI in jQuery UI version 1.9. Proof...
version added: 1.9 (Source: API.jQueryUI.com: Tooltip Widget.)
If you don't have a version of jQuery UI at version 1.9 or higher, you'll get the error: tooltip() is not a function().
Because jQuery 3.5.1 is getting larger it takes more time to load, in addition to the ordering of the JavaScript files, mentioned in many answers to this question, the way to go in addition to fixing the order which by the way does not always work, for Bootstrap tooltip option, a work around is to use a timeout based on jQuery loading time, example:
setTimeout(function () {
$("[title]").tooltip({
container: "body",
placement: "top",
delay: { show: 240, hide: 60 }
});
$("[title]").on("click", function () {
$(this).tooltip("hide");
});
}, 545*1.33); // 545ms timing to load jQuery.js + network estimated delay
To solve this you'll have to add to your gemfile:
gem 'jquery-ui-rails'
gem 'jquery-ui-themes'
Then you won't have the problem that jquery-ui isn't loading anymore Another solution is to require("bootstrap") in application.js seemingly in addition to import("bootstrap") and you have install jquery and bootstrap with yarn too I think this all pretty crazy

2 javascripts plugin not working together

I tried to implement 2 plugins in a page and when i introduce the 2nd one... the 1st plugins stops working .. can you please help me in this.. he is the page i am trying to build..
http://www.abc.com/home21
and here are the 2 plugins i am trying to use.
http://www.catswhocode.com/blog/how-to-integrate-a-slideshow-in-your-wordpress-theme
http://www.fyneworks.com/jquery/star-rating/
here is my code.. The rating script was working from beginning. i tried to add this slideshow in this page like
<link rel="stylesheet" href="testing/t1/css/layout.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="testing/t1/css/jd.gallery.css" type="text/css" media="screen" charset="utf-8" />
<script src="testing/t1/scripts/mootools.v1.11.js" type="text/javascript"></script>
<script src="testing/t1/scripts/jd.gallery.js" type="text/javascript"></script>
<script src="testing/t1/scripts/jd.gallery.transitions.js" type="text/javascript"></script>
<script type="text/javascript">
var newj = jQuery.noConflict();
function startGallery() {
var myGallery = new gallery(newj('myGallery'), {
timed: true,
showArrows: false,
embedLinks: false,
showCarousel: true,
defaultTransition: "continuoushorizontal"
});
} window.onDomReady(startGallery);
</script>
please help me how to solve this problem
You are using both Mootools and JQuery. These two javascript libraries overwrite each other.
http://www.catswhocode.com/blog/how-to-integrate-a-slideshow-in-your-wordpress-theme uses Mootools
http://www.fyneworks.com/jquery/star-rating/ uses Jquery
You will need to find plugins that only use jquery or mootools. See:
http://mootools.net/forge/
http://plugins.jquery.com/
For more plugins for each framework.
So the first one is MooTools, the second is jQuery. You can try to do $.noConflict()
http://api.jquery.com/jQuery.noConflict/
jQuery.noConflict();
function startGallery() {
var myGallery = new gallery($('myGallery'), {
timed: true,
showArrows: false,
embedLinks: false,
showCarousel: true,
defaultTransition: "continuoushorizontal"
});
} window.onDomReady(startGallery);
Regarding your using of $ all over your site, this would do it(based on docu):
<script type="text/javascript" src="other_lib.js"></script><!-- your mootools lib-->
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$.noConflict();
jQuery(document).ready(function($) {
// Code that uses jQuery's $ can follow here.
$('#id-here').click(function(e) {
alert('I can use $ here with no conflicts on other js libraries!');
});
});
// Code that uses other library's $ can follow here.
function startGallery() {
var myGallery = new gallery($('myGallery'), {
timed: true,
showArrows: false,
embedLinks: false,
showCarousel: true,
defaultTransition: "continuoushorizontal"
});
} window.onDomReady(startGallery);
</script>
If this still didn't work, take time to read the manual...you will get it eventually^^ Just know using .noConflict worked for me on a similar case I had a while back.
Though I'm curious where your star rating code is located...

Categories