trying to toggle stylesheet using button - javascript

I am attempting to switch stylesheets on my website using a button.
When I use this code, the stylesheet becomes nonexistent when I press the button and I cannot switch back unless I refresh the site. I do not know what is happening.
JavaScript
const stylesUrls = ["C:\Users\purrl\OneDrive\Desktop\Personal Coding\html\claires.css", "C:\Users\purrl\OneDrive\Desktop\Personal Coding\html\queen-of-hearts.css"];
window.onload = function(){
let switcherBtn = document.getElementById("themes");
switcherBtn.onclick = function() {
let style = document.getElementById('ss');
let stylesUrl = stylesUrls.shift();
style.href = stylesUrl;
stylesUrls.push(stylesUrl);
}
};
HTML
<link rel="stylesheet" href='C:\Users\purrl\OneDrive\Desktop\Personal Coding\html\claires.css' id="ss" type="text/css">
<button id="themes" type="button">Switch Theme</button>

Store the current index in a variable and change that instead.
const stylesUrls = ["foo", "bar"];
window.onload = function() {
const switcherBtn = document.getElementById("themes");
let currentIndex = 0;
switcherBtn.addEventListener("click", function() {
let style = document.getElementById('ss');
let stylesUrl = stylesUrls[currentIndex];
style.href = stylesUrl;
if (currentIndex === 0) {
currentIndex = 1;
} else {
currentIndex = 0;
}
});
}
If you're trying to do themes, you can change a class on the root html tag and include a style tag to both stylesheets and then use the corresponding class in each stylesheet.
Example
queen-of-hearts.css;
html.queen h1 {
color: red;
font-size: 20px;
}
html.queen div {
background-color: pink;
}
claires.css;
html.claire h1 {
color: blue;
font-size: 30px;
}
html.claire div {
background-color: green;
}
HTML;
<html class="queen"> <!-- Toggle between queen and claire using JavaScript -->
<head>
<link href="insert link to claires.css here" />
<link href="insert link to queen-of-hearts.css here" />
</head>
</html>
JS;
...
switcherBtn.addEventListener("click", function() {
if (document.documentElement.classList.contains("claire")) {
document.documentElement.classList.replace("claire", "queen");
} else {
document.documentElement.classList.replace("queen", "claire");
}
});
Demo

Related

Error on trying skip dialogue on my visual novel engine

I'm trying make my own visual novel engine for my game but i has some problem in my code,
In normally, text is writing like keyword write but when you press on anywhere on screen text complate automaticly. But when i clicked texts will combime and become like random text.
script.js
import {init} from "./main.js"
import Dialouge from "./dialogue.js"
let dialogues = [
"Merhaba buralarda yenisin galiba?",
"Tanıtmamı istermisin?"
]
const {body,head} = document
const html = head.parentNode
init(html,body)
let d = new Dialouge(body)
d.create()
let x = d.updateText(dialogues[0]);
let i = 1;
let sp = d.props.charPerSecond
document.onclick = () => {
if (x.lastStatus == false) {
if (d.props.charPerSecond == sp * 2) return;
setText({
charPerSecond: sp * 2
})
while(x.lastStatus==false) {}
setText({
charPerSecond: sp
})
} else {
x = d.updateText(dialogues[i])
i++;
}
}
main.js
export function init(html,body) {
html.style.height = body.style.height = "100%"
}
dialogue.js
const timer = ms => new Promise(res => setTimeout(res, ms))
export default class Dialogue {
#body
#element
#inner
#textP
constructor(body) {
this.#body = body
this.#element = document.createElement("div")
this.#inner = document.createElement("div")
this.#textP = {
speed: 0.1,
charPerSecond: 1
}
this.lastStatus = true
}
get props() {
return this.#textP
}
create() {
this.#body.style.position = "relative"
let element = this.#element
this.#inner.classList.add("dialouge-inner")
element.classList.add("dialogue")
element.append(this.#inner)
this.#body.append(element)
}
setText(data) {
this.#textP = {
...this.#textP,
...data
}
}
async updateText (datas) {
this.lastStatus = false
return new Promise(async res => {
datas = datas.split('')
this.#inner.innerText = ""
for (let i in datas) {
let data = datas.slice(i)
for (let j = 0; j < this.#textP.charPerSecond; j++) {
this.#inner.textContent += data[j]
}
await timer(this.#textP.speed * 1000);
}
this.lastStatus = true
res()
})
}
}
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>replit</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body></body>
<script src="script.js" type="module"></script>
</html>
css
html,body {
overflow:hidden;
padding: 0;
margin: 0;
box-sizing: border-box;
}
.dialogue {
position: absolute;
padding: 4px;
background: #000;
bottom: 1vmin;
left: 0;
width: 100%;
height: 20vmin;
}
.dialouge-inner {
width: 50%;
height: 95%;
margin: auto auto;
background: white;
}

Javascript Calling object methods within same object not working well

In This theme object i have created 2 properties.
I placed this.changeThemeTo(1); under the Event Listener, after that it worked. But i want to place it within if tag
But seems giving an error when put it within if
Uncaught TypeError: this.changeThemeTo is not a function
please help to fix this. Thanks..
var theme = {
changeThemeTo: function (theme_value) {
sessionStorage.removeItem('THEME'); // remove old theme from session storage
if (theme_value == 0) {
sessionStorage.setItem("THEME", 'dark');
} else if (theme_value == 1) {
sessionStorage.setItem("THEME", 'light');
}
document.body.className = sessionStorage.getItem("THEME");
},
init: function () {
document.body.classList.add("fade");
setTimeout(function () {
document.body.classList.remove("fade");
}, 100);
var themes = ['dark', 'light'];
themes.forEach(function (item) {
var button = document.querySelector("." + item);
if (button) {
button.addEventListener("click", function () {
if (item == "dark") {
this.changeThemeTo(0);
} else if (item == "light") {
this.changeThemeTo(1);
}
});
}
}, this);
}
}
window.onload = function () {
theme.init();
}
Here my html code
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.dark {
background-color: #191919;
color: #EEEEEE;
}
.light {
background-color: #EEEEEE;
color: #191919;
}
</style>
</head>
<body>
<div id="change-theme">
DARK
LIGHT
</div>
</body>
</html>
use self.changeThemeTo instead this.changeThemeTo. and define self = this as per the below code sample. also optimized some portion of the code.
var theme = {
changeThemeTo: function (theme_value) {
sessionStorage.setItem("THEME", theme_value);
document.body.className = theme_value;
},
init: function () {
document.body.classList.add("fade");
setTimeout(function () {
document.body.classList.remove("fade");
}, 100);
var themes = ['dark', 'light'];
var self = this;
themes.forEach(function (item) {
var button = document.querySelector("." + item);
if (button) {
button.addEventListener("click", function () {
self.changeThemeTo(item);
});
}
}, this);
}
}
window.onload = function () {
theme.init();
}
<style type="text/css">
.dark {
background-color: #191919;
color: #EEEEEE;
}
.light {
background-color: #EEEEEE;
color: #191919;
}
</style>
<div id="change-theme">
DARK
LIGHT
</div>

Javascript - next/previous buttons on slide show - New kid needs assistance

I am brand new at this so I apologize because I'm sure an intermediate could pull his or her answer from what's already been asked, but I need specific help.
I'm having trouble getting my "next" and "previous" buttons for my slideshow to work in Javascript. Once the user clicks through all 5 images, it needs to return to the first image, ready to click through again-- a continuous loop. I think arrays are supposed to be utilized. What am I missing?
Thank you!!
var imageCache = [];
var imageItem = 0;
var images = 0;
var captionNode;
var imageNode;
var $ = function (id) {
return document.getElementById(id);
}
window.onload = function () {
var listNode = $("image_list");
var nextButton = $("next");
var previousButton = $("previous");
captionNode = $("caption");
imageNode = $("image");
var links = listNode.getElementsByTagName("a");
var i, linkNode, image;
for ( i = 0; i < links.length; i++ ) {
linkNode = links[i];
// Pre-load image and copy title properties.
image = new Image();
image.src = linkNode.getAttribute("href");
image.title = linkNode.getAttribute("title");
imageCache.push(image);
}
// Now record the total images we have.
images = imageCache.length;
// Set up the button handlers.
nextButton.onclick = nextButtonClick;
previousButton.onclick = previousButtonClick;
}
function nextButtonClick() {
}
function previousButtonClick() {
}
article, aside, figure, figcaption, footer, header, nav, section {
display: block;
}
body {
font-family: Arial, Helvetica, sans-serif;
width: 380px;
margin: 0 auto;
padding: 20px;
border: 3px solid blue;
}
h1, h2, ul, p {
margin: 0;
padding: 0;
}
h1 {
padding-bottom: .25em;
color: blue;
}
h2 {
font-size: 120%;
padding: .5em 0;
}
ul {
display: none;
}
img {
height: 250px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Slide Show</title>
<link rel="stylesheet" href="main.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script src="slide_show.js"></script>
</head>
<body>
<section>
<h1>Fishing Slide Show</h1>
<ul id="image_list">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<h2 id="caption">Casting on the Upper Kings</h2>
<p>
<img src="images/casting1.jpg" alt="" id="image">
</p>
<input type="button" value="Previous" name="previous" id="previous">
<input type="button" value="Next" name="next" id="next">
</section>
</body>
</html>
You have the following variables:
var imageCache = [];
var imageItem = 0;
var images = 0;
Presumably imageItem is the index of the currently displayed image (e.g. 0 for the first one) and images is the number of images (i.e. imageCache.length). To get the next image:
imageItem = ++imageItem % images;
var nextImage = imageCache[imageItem];
This will wrap around to zero when imageItem reaches the number of images in the cache. Similarly for previous:
imageItem = (--imageItem + images) % images;
var prevImage = imageCache[imageItem];
so that when imageItem reaches 0, subtracting 1 goes to -1 and adding imageCache.length sets it to the last image. The rest of the time it's left at imageItem - 1.
It's up to you to fill in the rest of the code. :-)
I would use an array zipper to implement the next and prev functions. An array zipper is a data structure that allows you to move forward and backward through an array.
function ArrayZipper(array) {
var length = array.length, index = 0;
this.getCurrent = function () {
return array[index];
};
this.getNext = function () {
return array[index = (index + 1) % length];
};
this.getPrevious = function () {
return array[index = (length + index - 1) % length];
};
}
You can use an array zipper to create a slide show as follows:
var zipper = new ArrayZipper([ "black"
, "blue"
, "green"
, "cyan"
, "red"
, "magenta"
, "yellow"
, "white"
]);
var style = $("color").style;
style.backgroundColor = zipper.getCurrent();
$("next").addEventListener("click", function () {
style.backgroundColor = zipper.getNext();
});
$("prev").addEventListener("click", function () {
style.backgroundColor = zipper.getPrevious();
});
function $(id) {
return document.getElementById(id);
}
function ArrayZipper(array) {
var length = array.length, index = 0;
this.getCurrent = function () {
return array[index];
};
this.getNext = function () {
return array[index = (index + 1) % length];
};
this.getPrevious = function () {
return array[index = (length + index - 1) % length];
};
}
#color {
height: 100px;
width: 100px;
}
<div id="color"></div>
<button id="next">Next</button>
<button id="prev">Prev</button>
Hope that helps.

Traverse through all HTML tags and modify their style

I'm trying to automatically adjust LTR styles to RTL with Javascript.
And for some reason, the Div elements are not affected
This is my HTML:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="rtl.js"></script>
<style type="text/css">
.r {float: right;}
.l {float: left;}
</style>
</head>
<body>
<div class="l">A</div>
<div class="r">B</div>
</body>
</html>
And this is the content of rtl.js
var allStyles=['azimuth','background','background-attachment','background-color','background-image','background-position','background-repeat','border','border-collapse',
'border-color','border-spacing','border-style','border-top','border-right','border-bottom','border-left','border-top-color','border-right-color','border-bottom-color',
'border-left-color','border-top-style','border-right-style','border-bottom-style','border-left-style','border-top-width','border-right-width','border-bottom-width',
'border-left-width','border-width','bottom','caption-side','clear','clip','color','content','counter-increment','counter-reset','cue','cue-after','cue-before',
'cursor','direction','display','elevation','empty-cells','float','font','font-family','font-size','font-size-adjust','font-stretch','font-style','font-variant',
'font-weight','height','left','letter-spacing','line-height','list-style','list-style-image','list-style-position','list-style-type','margin-top',
'margin-right','margin-bottom','margin-left','marker-offset','marks','max-height','max-width','min-height','min-width','orphans','outline','outline-color',
'outline-style','outline-width','overflow','padding-top','padding-right','padding-bottom','padding-left','page','page-break-after','page-break-before',
'page-break-inside','pause','pause-after','pause-before','pitch','pitch-range','play-during','position','quotes','richness','right','size','speak','speak-header',
'speak-numeral','speak-punctuation','speech-rate','stress','table-layout','text-align','text-decoration','text-indent','text-shadow','text-transform','top',
'unicode-bidi','vertical-align','visibility','voice-family','volume','white-space','widows','width','word-spacing','z-index','border-radius','border-top-left-radius',
'border-top-right-radius','border-bottom-left-radius','border-bottom-right-radius','border-image','border-image-outset','border-image-repeat','border-image-source',
'border-image-slice','border-image-width','break-after','break-before','break-inside','columns','column-count','column-fill','column-gap','column-rule',
'column-rule-color','column-rule-style','column-rule-width','column-span','column-width','#keframes','animation','animation-delay','animation-direction',
'animation-duration','animation-fill-mode','animation-iteration-count','animation-name','animation-play-state','animation-timing-function','backface-visibility',
'perspective','perspective-origin','transform','transform-origin','transform-style','transition','transition-delay','transition-duration','transition-timing-function',
'transition-property','background-clip','background-origin','background-size','overflow-x','overflow-y','overflow-style','marquee-direction','marquee-play-count',
'marquee-speed','marquee-style','box-shadow','box-decoration-break','opacity']
//'margin','padding'
function applyStyles($el,css_props,css_vals)
{
$el.removeAttr('style');
var i=0;
for (i=0;i<css_props.length;i++)
{
$el.css(css_props[i],css_vals[i]);
}
}
function str_swap(str,a,b)
{
return str.replace(b,"tovtov").replace(a,b).replace("tovtov",a);
}
function isCSSEmpty(val)
{
return (val == undefined)||(val == '')||(val == 'none')||(val == 'normal');
}
function transform_rtl()
{
var rtl='rtl_rtl_rtl';
jQuery('*').each(function() {
$el=jQuery(this);
if ($el.hasClass(rtl))
return;
var css_props = [];
var css_vals = [];
var i;
for (i=0;i<allStyles.length;i++)
{
var css_prop=allStyles[i];
var css_val=$el.css(css_prop);
if (!isCSSEmpty(css_val)){
if (css_prop.indexOf("left")>=0)
{
css_prop=css_prop.replace("left","right");
}
else if(css_prop.indexOf("right")>=0)
{
css_prop=css_prop.replace("right","left");
}
else
{
css_val=str_swap(css_val,"right","left");
css_val=str_swap(css_val,"rtl","ltr");
}
css_props.push(css_prop)
css_vals.push(css_val)
$el.css(css_prop,'');//clear styling
}
}
applyStyles($el,css_props,css_vals);
$el.css('diretion','rtl');
this.addClass(rtl);
});
}
jQuery(document).ready(transform_rtl);
replace jQuery('*').each(function() { with $(document).children('*').each(){ .I guess this should work!

Get content from iFrame, where is the error?

I'd like to get the security zone (Internet zone / local intranet) for a number of URL's which are in the same domain. I thought the best solution would be to get this through iFrame.
#Teemu. Code works now. Thank you very much. But one problem so far: It displays the wrong text. Although the page is in trusted zone (local intranet) he displays "untrusted" (Internet zone). Any idea why?
<html>
<head>
<script type="text/javascript">
function getZone() {
var text = new Array();
document.getElementsByClass('iframeNames');
var test;
for (var i = 0; i < document.frames.length; i++) {
try {
test = document.frame[i].contentWindow.document;
text[i] = "Trusted (Local Intranet)";
} catch (e) {
text[i] = "Untrusted (Internet Zone)";
}
} //end-for
var showText = getElementsByClass("zone");
for (var i = 0; i < showText.length; i++) {
setText(showText[i], text[i]);
};
} //end getZone()
function setText(showText, text) {
showText.innerHTML = text;
} //end setText
if (document.getElementsByClassName) {
getElementsByClass = function (classList, node) {
return (node || document).getElementsByClassName(classList);
};
}
</script>
</head>
<style type="text/css">
tr:nth-child(2n) {
background-color: #ddd;
}
.format {
background-color: #ffff;}
#formatierung {
margin-left: 10px;
margin-top: 30px;
font-family: Arial;
font-size: 13px;
}
</style>
<body>
<iframe src = "http://example.com" class = "iframeNames" width = "0"
height ="0"></iframe>
<iframe src = "http://example.com/index/" class = "iframeNames" width = "0"
height = "0"></iframe>
<script type = "text/javascript">
window.onload = function() {
getZone();
};
</script>
<div id = "formatierung">
<table width = "100%">
<tr class = "format"><td><h2>System</h2></td><td><h2>Check Security-Zone</h2></td></tr>
<tr><td>example1</td><td class = "zone"></td></tr>
<tr><td>example2</td><td class = "zone"></td></tr>
</table>
</div>
</body>
</html>
You can try this:
var test;
for (var i = 0; i < document.frames.length; i++) {
try {
test = document.frames[i].document;
text[i] = "Trusted (Local Intranet)";
} catch (e) {
text[i] = "Untrusted (Internet Zone)";
}
}
With this code you won't need isTrustedIE() at all.
Like I said in my previous comment, frames[] is a collection of the "window" objects in the document. This code just checks, if it can get a reference to the document in the iframe. It's not possible, when iframe's content is loaded from cross-origin source.

Categories