Multi theme website - javascript

I want to change the color of the whole website when I click on a button. This will remain whenever I do not change. If I go to another page, the color should remain the same as what I previously selected.
E.g. https://india.gov.in/
In the top header, when select the color black, whole website will be black until we do not change. Same I want functionality.
I have done to change the color on current but not wholw page. When I go to another page default colors is coming.
<script>$(document).ready(function () {
$('#demo-wrapper ul li').on('click', function () { var path = $(this).data('path');$('#color-switcher').attr('href', path); });
}); </script>
<ul class="dropdown-menu multicolors-name">
<li data-path="Content/theme/assets/admin/css/custom_website.css‌​">
Green</li><li data-path="Content/theme/assets/admin/css/blue.css"><a href="#" >Blue</a>
</li>
</ul>

A way to do this, get a master.css file. Inside this file you can import your other css files. Like this:
#import 'header.css'
#import 'main.css'
Then you can have another master-theme2.css where you would import other css files. The way to change your master.css file is like this:
https://stackoverflow.com/a/22445820/4673847
For keeping the theme per page, you should use sessions or cookies

The easiest way to do this is with help of some css preprocessor for example LESS. Then you can loop over prepared color schema setting:
.generate-widget-colors(#list) {
.iter(length(#list));
.iter(#index) when (#index > 0) {
.iter(#index - 1);
#item: extract(#list, #index);
#key: extract(#item, 1);
#color: extract(#item, 2);
.color-schema-#{key} {
color: #color;
}
.background-color-schema-#{key} {
background-color: #color;
}
div.connect-container.wizard-schema-#{key} > div > div > div > h3 {
color: #25414c;
}
div.connect-container.wizard-schema-#{key} .widget-icon {
color: #Green;
}`
}
}
.generate-widget-colors(#WidgetColors);
This is my own example when I pass the color(key) value into this loop from my backend and all my widgets get new colors. And for saving the schema you can use browsers local storage for example or if you have an authentication then ofc store user schema in db

in layout apply this jquery. Get the selected color value and apply it here.
window.jQuery("#ButtonId").click(function ()
{
window.jQuery('#Layoutid').css("color", "selectedcolor");
});

You can make use of HTML5 local storage or cookies to achieve it. You need to store the selected color and then retrieve it on window load.
I have created a working fiddle based on HTML 5 local storage. Just select a color and reload the fiddle, the background color will remain the same as you selected.
You can switch CSS files with something like this.
<span class="css-selector" id="style1" data-css="path_to_style1.css">Theme 1</span>
<span class="css-selector" id="style2" data-css="path_to_style2.css">Theme 2</span>
$(".css-selector").click(function() {
$("head link#maincss").attr("href", $(this).data("css")); //where main css is placed in head like <link rel="stylesheet" id="maincss" type="text/css" href="path_to_style1.css">
}
And for simple color switching, you can use this code:
<div class="selector">
<span class="color red" data-color="#990000"></span>
<span class="color green" data-color="#009900"></span>
<span class="color blue" data-color="#000099"></span>
</div>
<div class="content">
India is a "Sovereign, Socialist, Secular, Democratic Republic" with a parliamentary system of government. This section seeks to introduce the Constitution of India, its origin, the Parliament, various Acts and Rules that govern the nation, Documents, Public Notifications, Welfare Schemes and Application Forms to avail them, apart from updates on what’s happening around us. Know the "Who's Who" of the Indian Government and check out a range of such vital information that may help you in your daily life.
</div>
$(document).ready(function(){
var themeColor="#ffffff"; // define default theme color
if(typeof(Storage) !== "undefined") {
if (localStorage.themeColor) {
themeColor = localStorage.themeColor //get stored color
}
$('.content').css('background', themeColor); set stored color as background
}
});
$('.selector .color').click(function(){
themeColor = $(this).data("color");
$('.content').css('background', themeColor); //set selected color as background
if(typeof(Storage) !== "undefined") {
localStorage.themeColor = themeColor; // store selected color
};
});
.color{
display:inline-block;
height:20px;
width:20px;
border-radius:50%;
margin:5px;
cursor:pointer;
}
.red{
background-color:red;
}
.green{
background-color:green;
}
.blue{
background-color:blue;
}
Check it here. https://jsfiddle.net/hcfejaez/3/

Related

HTML Local Storage Icon Change and Dark Mode with JavaScript

I have made a dark mode button with my own dark theme. The theme is saved by Local Storage. Also when I click the button, then it's icon change (moon to sun). But if I reload the page, the site is still in dark mode but the button icon's is the moon again. So heres a link which show you the problem if youo don't understant what i am talking about. (https://postimg.cc/yg6Q3vq0)
Also heres my code:
//This is the darkmode script.
function darkmode() {
const wasDarkmode = localStorage.getItem('darkmode') === 'true';
localStorage.setItem('darkmode', !wasDarkmode);
const element = document.body;
element.classList.toggle('dark-mode', !wasDarkmode);
}
function onload() {
document.body.classList.toggle('dark-mode', localStorage.getItem('darkmode') === 'true');
}
//End
//And this is the code which change the button's icon
$('button').on('click', fav);
function fav(e) {
$(this).find('.fa').toggleClass('fa-moon-o fa-sun-o');
}
//So I would like to combine the 2 codes. I mean to add the icon code to Local Storage.
.card {
color: yellow;
background-color: blue;
}
.dark-mode .car {
color: blue;
background-color: yellow;
}
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<a style="padding: 0 !important;"><button class="darkmode" onclick="darkmode()"><i class="fa fa-moon-o"></i></button></a>
<div class="card">
<h1>Title</h1>
<p>Text<//p>
<h2>Another text..</h2>
</div>
</body>
</html>
The browser just renders the HTML as written. Your HTML says to render <i class="fa fa-moon-o"></i>, so that's what the browser shows. In other words, it will always show the moon icon by default.
You need to perform some kind of check on page load to see if the icon should be changed.
Something like this might work:
// when the document is ready
$(document).ready(function () {
// check if dark mode is enabled
if (localStorage.getItem('darkmode') === 'true') {
// if it is, change the moon icon to a sun icon
('.fa').toggleClass('fa-moon-o fa-sun-o');
}
});

javascript color toggles between two links working, not resetting when they need to

I have two links popularity and new. if I click "popularity" it should turn green until I click "new". and vice versa for "new". And this works great. But thing is when I click home button that's in my navbar, the green color on the link should be gone. they should go back to the color they were before they are clicked.
my code
<div id="Space">
<ul id="shouldwork">
<li role="presentation" class="sort">
<a class="norang" href="/?sort=score&page=1" style="text-decoration:none;">popularity</a>
</li>
<li role="presentation" class="date">
<a class="updated" href="/?sort=date&page=1" style="text-decoration:none;">new</a>
</li>
</ul>
</div>
<script>
//on page load
var ul_li_a = $("ul#shouldwork>li>a");
var lastClickTag = localStorage.getItem("last_clicked");
ul_li_a.css("color", "black");
if(lastClickTag){
$("."+lastClickTag).css("color", "green")
}
$('ul#shouldwork>li').on("click", function(){
ul_li_a.css("color", "black");
$(this).children("a").css("color", "green");
localStorage.setItem("last_clicked", $(this).children("a").attr("class"));
});
</script>
and in navbar I have
<div class="navbar-header">
<a class="navbar-brand" href="{% url 'index' %}">home</a>
</div>
I would do this with an .active class in CSS in order to make it more modular and easy to understand. Then, I would change the color based on your query strings, rather than using local storage.
I didn't have a way to test this so let me know if it works. If not, let me know what error is displaying in the console. I'm sure I may have missed something in the JS.
Here is a codepen if you'd rather look at it there: http://codepen.io/anon/pen/xVGYWE?editors=1111
HTML (links are removed as they broke in codepen, added class .link for better targeting in jQuery)
<div id="Space">
<ul class="shouldwork">
<li role="presentation" class="sort">
<a class="link norang" href="#">popularity</a>
</li>
<li role="presentation" class="date">
<a class="link updated" href="#">new</a>
</li>
</ul>
</div>
CSS
.link {
color: blue;
text-decoration: none;
}
.link:hover {
color: navy;
text-decoration: none;
}
.link.active {
color: green;
}
jQuery
// change on click
var link = $('.link');
link.on("click", function(){
// remove any active classes
link.removeClass("active");
// add active class to link that was clicked
$(this).addClass("active");
});
// set up get query strings from URL
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// see if the page is indeed sorted
var sort = getParameterByName('sort')
// if it has a query string of sort=score, make that active
if ( sort == "score") {
$(".sort a").addClass("active");
}
// if it has a query string of sort=date, make that active
if ( sort == "date") {
$(".date a").addClass("active");
}
Why should they go back to the original color? You never told them to.
$('.navbar-brand').on('click',function(){
ul_li_a.css("color", "black");
})
You could utilize both .addClass and .removeClass, and create another CSS class that changes the color back when you click the home button. This would be more seamless if you took the css out of your js code, and just use these two methods to switch between the classes you need on the home button click event.
edit: or what he said ^. There are many options.
Based on your problem description, and a quick scan of your code, it looks like you are properly setting the color when the two items themselves are clicked, but you have no function to handle unsetting the color when something else is clicked ... i.e. in your function that fires on-click, just check that if neither is used, clear the green color.
Alternatively, you could use something like is used here ... i.e. a conditional something along the lines of this: if(a[i].href.split("#")[0] == window.location.href.split("#")[0]). Then, just apply the green color if either of your two links are active.
Hope this helps!
If you can use ids for links, change your code as below. Check demo - Fiddle.
var ul_li_a = $("ul#shouldwork>li>a");
var lastClickTag = localStorage.getItem("last_clicked");
if(lastClickTag){
$("#"+lastClickTag).addClass('green');
}
ul_li_a.on("click", function(){
ul_li_a.removeClass('green');
$(this).addClass('green');
localStorage.setItem("last_clicked", this.id);
});
$('.navbar-brand').click( function() {
ul_li_a.removeClass('green');
$("#"+lastClickTag).addClass('green');
})
HTML:
<ul id="shouldwork">
<li role="presentation" class="sort">
<a id="norang" href=".." style="text-decoration:none;">popularity</a>
</li>
<li role="presentation" class="date">
<a id="updated" href=".." style="text-decoration:none;">new</a>
</li>
</ul>
CSS:
.green {
color: green;
}
Clearing your lastClickTag from the local storage must resolve your issue along with this code.
$('.navbar-brand').on('click',function(){
localStorage.removeItem("last_clicked");
})
remove this local storage. So your if(lastClickTag){ function will not be executed, And your color will remain black.

Javascript - simplifying a bunch of long repetative hide/show functions

Things have gotten out of hand for me. What started off as the simplest solution has ballooned to the point where it is no longer manageable. I need to come up with a way to simplify a process.
Currently I have a map with pins denoting specific countries world-wide. As the mouse hovers over a pin, a hidden div appears. When you mouse over another one, the previous div disappears and a new one opens. I started with like 5 of these and it wasn't an issue but I keep getting requests for more and want to manage the script in a different way now.
$('#PH1').mouseenter(function () {
$('#BO2').hide();
$('#US2').hide();
$('#UK2').hide();
$('#CH2').hide();
$('#BZ2').hide();
$('#QC2').hide();
$('#OT2').hide();
$('#VA2').hide();
$('#RU2').hide();
$('#JT2').hide();
$('#HK2').hide();
$('#SH2').hide();
$('#BJ2').hide();
$('#XI2').hide();
$('#BE2').hide();
$('#AT2').hide();
$('#FR2').hide();
$('#MX2').hide();
$('#PH2').show();
});
$('#PH1').click(function (e) {
e.stopPropagation();
});
$('#mint').click(function () {
$('#PH2').hide();
});
In this instance div id #PH1 is the pin, when the mouse enters the div it hides all of the other div's #**2 and displays the one related to #PH1, which is #PH2
This list is repeated for each DIV. Every time I need to add a new DIV I need to make each existing list longer as well as create a new one. How can this process be made much simpler?
Thats not a right way to do this, you should use classes for this. But their is a wayaround for this all you need to is add a class add class ele1 to all #**1 and ele2 to all #**2:
then
$('.ele1').mouseenter(function () {
$(".ele2").hide();
var id = this.id;
var newId = id.substring(0,2)+"2";
$("#"+newId).show();
});
Make a loop:
var all= ['#BO2', '#US2', '#UK2', '#CH2', '#BZ2', '#QC2', '#OT2', '#VA2', '#RU2', '#JT2', '#HK2', '#SH2', '#BJ2', '#XI2' , '#BE2', '#AT2', '#FR2', '#MX2', '#PH2']
all.forEach(function (i){
$(i).hide();
});
Use a class selector on all of the DIVs you want to hide/show instead of an ID.
First, add a shared class to all DIVs so we target all of them by class.
HTML: class="hidden-divs"
jQuery: $('.hidden-divs').hide();
Then show the relevant DIV.
$('#PH2').show();
Using your first example, it would look like this:
$('#PH1').mouseenter(function () {
$('.hidden-divs').hide();
$('#PH2').show();
});
You can use jquery to hide multiple divs if you can select them. For example, suppose you have a common class ".map_divs" on all your divs, you could easily do:
$(".map_divs").hide();
On a side-note, you could solve all this on CSS, using :hover. For example:
.map_divs:hover {
display: block;
}
If you can edit the div's yourself (if it is not generated by a library) I would do it like this.
Add a common class to all your divs. Then on each div, add a data attribtue to the related id.
<div class="pin" id="PH1" data-rel="PH2"></div>
Then you can have a simple function like this:
$(".pin").mouseenter(function() {
var relatedId = $(this).data("rel");
$(".pin[id$='2']").hide(); // Hide all pins with id ending in 2
$("#" + relatedId).show() //show PH2
})
Using classes might be a better option here. You can then just attach the mouseenter event on document ready to all pins. This will work for an infinite number of pins too.
$('.pin').mouseenter(function () {
$('.popup').removeClass('show');
var id = this.id.split('_')[1];
$('#popup_' + id).addClass('show');
});
.pin {
width:30px;
height:30px;
margin-bottom:20px;
background-color:red;
}
.popup {
display:none;
width:100px;
height:100px;
margin-bottom:20px;
background-color:blue;
}
.popup.show {
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pin_1" class="pin"></div>
<div id="popup_1" class="popup"></div>
<div id="pin_2" class="pin"></div>
<div id="popup_2" class="popup"></div>
If your div element is ordered like below, you can get the same result using css only, which will increase speed and overall experience (especially on phones and tablets).
When "hover" the yellow squares, the popup will be visibible even when "hover" the popup.
.pin {
width:30px;
height:30px;
margin-bottom:20px;
background-color:red;
}
.popup {
display:none;
width:100px;
height:100px;
margin-bottom:20px;
background-color:blue;
}
.pin:hover + .popup {
display:block;
}
.pin.type2 {
background-color:yellow;
}
.pin.type2:hover .popup {
display: inline-block;
margin-top: 30px;
}
<div id="pin_1" class="pin"></div>
<div id="popup_1" class="popup"></div>
<div id="pin_2" class="pin"></div>
<div id="popup_2" class="popup"></div>
<div id="pin_3" class="pin type2"><div id="popup_3" class="popup"></div></div>
<div id="pin_4" class="pin type2"><div id="popup_4" class="popup"></div></div>

jquery; $().css failing to update style of object

so I'm getting a div, supplied by an rss feed, and the styles are being changed, so the links within the div appear with a grey color instead of it's original blue style.
this comes from a style sheet included on the local page.
here's a snippet of the code I get from the rss feed;
...<td style="padding-left:5px; padding-right:5px; padding-bottom:5px; line-height: 150%">
<a href="http://www.blah.co.uk/destinations/destination~GRJ~George/" target="_blank">
<span style="color:0e6ac8;">
<span style="font-size:12px;">
<strong>Joburg-George</strong>
</span>
</span>
</a>
</td>...
Note the inline color style over here; <span style="color:0e6ac8;">
This style is being overridden by the style in the stylesheet.
previously I just put some jquery after the included block, to change that color, but the team rejected my pull request as it was too specific;
<div id="marketing_block" style="padding-left:0px;margin-left:0px;width:890px;">
<?php echo $marketing_content['post_content']; ?>
</div>
<script type="text/JavaScript">
$("#marketing_block a span").each(function(){
$(this).css('color', '#0E6AC8');
});
</script>
The problem is that the rss feed content will change from time to time, so I have to keep all the inline styling for all tags inside of the #marketing_block div.
update:
I just tried this and got no errors, but yet the links remain grey;
<script type="text/JavaScript">
$("#flight_marketing_block").find("*").each(function(){
//$(this).css('color', '#0E6AC8');
var style = $(this).attr("style");
if(style != undefined && style != ''){
try{
style = "'" + style.replace(/:/gi, "':'").replace(/;/gi, "';'").replace(/;/g, ",").replace(/\'\s/, "'").replace(/.[\'|,]\s?$/, '') + "'";
alert("style: " + style);
for(var index in style.split(',')){
$(this).css(index.split(':')[0], index.split(':')[1]);
}
}catch(e){
alert("problem: " + e.message)
}
}
});
</script>
You cannot change the style of RSS Feed box. bcoz it is inside iframe, and you cannot access element inside iframe without having id of that iframe, and id of iframe given by RSS feed is changes on every refresh

How can I create several javascript image buttons?

I am new at creating websites in HTML. I use free for all SeaMonkey software. So, I want to create several image buttons which would change when user moves the mouse over the image. I already have created 3 images for the different stages of each button (normal, active and clicked). I wrote this code for the first button:
<body>
<a href="first.html" onmouseover="return changeImage(jsbutton)" onmouseout="return changeImageBack(jsbutton)">
<img name="jsbutton" src="first normal.png" alt="first">
<script type="text/javascript">
function changeImage() {
document.images["jsbutton"].src= "first active.png";
return true;
}
function changeImageBack() {
document.images["jsbutton"].src = "first normal.png";
return true;
}
</script>
</a>
</body>
And it works. But when I did the same for second button, it didn't work and in addition to that, the first one has stopped working too. What do I have to change to make it work properly?
Update:
For second button I wrote:
<a href="second.html" onmouseover="return changeImage(jsbutton)"
onmouseout="return changeImageBack(jsbutton)">
<img name="jsbutton" src="second normal.png" alt="second">
<script type="text/javascript">
function changeImage()
{
document.images["jsbutton"].src= "second active.png";
return true;
}
function changeImageBack()
{
document.images["jsbutton"].src = "second normal.png";
return true;
}
</script> </a>
</body>
You are using the same "name" attribute i.e. jsbutton for the both the images. Use different name attributes. Also css :hover is a better way to do this problem.
Your JavaScript is failing because you are using the same name attribute for both images. Each element must have a unique name.
That being said, the functionality you are after is already built in to CSS, so unless you have a specific requirement for this to be JavaScript, this is a problem far better solved in CSS, using :hover.
So in your html:
In your CSS:
#firstButton {
background-image: url('first normal.png');
display:block;
height: [height of img];
width: [width of img];
}
#firstButton:visited {background-image: url('first visited.png'); }
#firstButton:hover { background-image: url('first active.png'); }
And you are done! No use recreating functionality already built in to CSS!
Well you can also use inline javascript for this purpose as it is pretty simple:
<a href="first.html" >
<img onmouseover="this.src = 'second active.png'; " src="second normal.png" onmouseout="this.src = 'second normal.png'; " alt="first" />
</a>
Here is the Demo , in which I used some random images urls
Hope this helps.

Categories

Resources