Fading in and out CSS stylesheet with Javascript - javascript

I am trying to implement more elegant elements in my site using Javascript.
Snippet
<script>
function nightmode(){
var el = document.getElementById('myStyles'); // get stylesheet
if ( el !== null ) { // if it exists
el.parentNode.removeChild(el); // remove it
} else { // if not, add it
var oLink = document.createElement("link")
oLink.id = 'myStyles';
oLink.href = "nightmode3.css";
oLink.rel = "stylesheet";
oLink.type = "text/css";
document.body.appendChild(oLink);
}
}
</script>
That switches the site to nightmode. If you click the button, it switches nightmode on, or off. Simple enough.
However, I'd like a .5 second fadein/fadeout effect on each click, to make it less jarring. I've tried adding it via CSS, but that only works for fade in. How can I get both fade in and fade out effects?

Here are a few different ways to keep transitions working whenever you switch between styles. The underlying thing to keep in mind is that you have to have a transition rule available for the transition to happen. If you have it in one style but not the other, it will only happen whenever you change to the style that has it because otherwise there is no rule saying that there needs to be a transition.
<link> Swapping Method
Basically, make sure that the transition rules are always available. If they are in your night/day stylesheet but not other, then there is no longer a rule to transition. That's why it would only work whenever you fade in.
Ideally though, you would probably want both sets of rules in a single file and then change between the active styles using a class on the <body> tag. However, there are certainly use cases where you might want to still use two separate stylesheets that aren't both loaded simultaneously. For example a high contrast stylesheet that might not be used by all users would waste memory. However, I'd still probably use the class attribute on the <body> tag in case I ever wanted to combine them.
index.html
<html>
<head>
<title>CSS Test</title>
<link rel="stylesheet" href="base.css">
<script src="index.js"></script>
</head>
<body>
<main>
<h1>Hello!</h1>
<p>I am text</p>
<ul>
<li>
<button id="day_mode">Day</button>
</li>
<li>
<button id="night_mode">Night</button>
</li>
</ul>
</main>
</body>
</html>
index.js
/*jslint browser:true*/
(function () {
"use strict";
function addStylesheet(name, loc) {
var sheet = document.createElement("link");
sheet.id = name;
sheet.href = loc;
sheet.rel = "stylesheet";
sheet.type = "text/css";
document.head.appendChild(sheet);
return sheet;
}
function removeStylesheet(sheet) {
sheet.parentNode.removeChild(sheet);
//document.getElementById(name).removeChild();
}
function go() {
var dayButton = document.getElementById("day_mode"),
nightButton = document.getElementById("night_mode"),
daySheet,
nightSheet;
dayButton.addEventListener("click", function (e) {
e.preventDefault();
if (!daySheet) {
if (nightSheet) {
removeStylesheet(nightSheet);
nightSheet = null;
}
daySheet = addStylesheet("day", "day.css");
}
});
nightButton.addEventListener("click", function (e) {
e.preventDefault();
if (!nightSheet) {
if (daySheet) {
removeStylesheet(daySheet);
daySheet = null;
}
nightSheet = addStylesheet("night", "night.css");
}
});
}
document.addEventListener("DOMContentLoaded", go);
}());
base.css
h1 {
transition: color 1s;
}
p {
transition: background-color 1s, color 1s;
}
day.css
h1 {
color: orange;
}
p {
background-color: yellow;
color: red;
}
night.css
h1 {
color: blue;
}
p {
background-color: black;
color: blue;
}
<body> Class Namespacing
If you do want to try the <body> class method, here is a short implementation showing how to do that.
The basics of this is that you have a namespace for each version, day/night, of the CSS that you want to use and you prefix those mode rules with the relevant namespace.
Then, using JavaScript, you would remove or add the namespace class from your <body> tag using document.body.classList.add() and document.body.classList.remove().
/*jslint browser:true*/
(function() {
"use strict";
function go() {
var dayButton = document.getElementById("day_mode"),
nightButton = document.getElementById("night_mode");
dayButton.addEventListener("click", function(e) {
e.preventDefault();
document.body.classList.remove("night");
document.body.classList.add("day");
});
nightButton.addEventListener("click", function(e) {
e.preventDefault();
document.body.classList.remove("day");
document.body.classList.add("night");
});
}
document.addEventListener("DOMContentLoaded", go);
}());
h1 {
transition: color 1s;
}
p {
transition: background-color 1s, color 1s;
}
body.day h1 {
color: orange;
}
body.day p {
background-color: yellow;
color: red;
}
body.night h1 {
color: blue;
}
body.night p {
background-color: black;
color: blue;
}
<html>
<head>
<title>CSS Test</title>
<link rel="stylesheet" href="index2.css">
<script src="index2.js"></script>
</head>
<body class="day">
<main>
<h1>Hello!</h1>
<p>I am text</p>
<ul>
<li>
<button id="day_mode">Day</button>
</li>
<li>
<button id="night_mode">Night</button>
</li>
</ul>
</main>
</body>
</html>
Alternate Stylesheet Relation
One other thing to note, is that if you use the <link ... rel="stylesheet alternate" ...> approach, the transitions will also still work. I'm not sure what browsers still provide a means for users to switch their preferred rendering style manually. Chrome does not provide a way, but FireFox does. See the below screenshot.
Here is the markup I'm using for my <head> element.
<head>
<title>CSS Test</title>
<link rel="stylesheet" href="base.css">
<link rel="stylesheet" href="day.css" title="Day">
<link rel="stylesheet alternate" href="night.css" title="Night">
<script src="index.js"></script>
</head>

Related

coverting hover jquery code into javascript

I need help converting a Jquery code into a javascript code where it changes the border radius of a div when hovering over it.
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="SampleQ3.css" />
</head>
<body>
<div>
<h4>Pasta</h4>
</div>
<script src="SampleJavaScript.js"></script>
</body>
</html>
JS
$(document).ready(function () {
$("div").hover(function () {
$(this).css("border-radius", "0%");
}, function () {
$(this).css("border-radius", "200px 200px 200px 200px");
});
});
You can do all of that only using css, but I will provide both solution js and css.
javascript code:
let divs = document.getElementsByTagName("div");
for(div of divs) {
div.addEventListener("mouseenter", function( event ) {
event.target.style.borderRadius = 0%;
}, false);
div.addEventListener("mouseover", function( event ) {
event.target.style.borderRadius = '200px';
}, false);
}
To do the same with css you can add a class to make it easer to target.
// css
<style>
.div-round {
border-radius: 200px;
}
.div-round:hover {
border-radius: 0%;
}
</style>
//add class to div
<div class='div-round'>...</div>

Can you style an element with JavaScript without adding a style attribute?

When you write element.style = "..." in JavaScript in adds the style attribute to the element you add the style to. Is there a way to add a style without the style attribute, without any libraries?
If you can come up with a selector that targets the element, another option is to append a stylesheet that contains that selector:
const styleTag = document.head.appendChild(document.createElement('style'));
styleTag.textContent = 'div { color: blue; }';
<div>Some div</div>
It'd be more reliable if you're permitted to change the element in some way, like add a class or other attribute:
const div = document.querySelector('div');
const className = `_${('' + Math.random()).slice(2)}`;
div.classList.add(className);
const styleTag = document.head.appendChild(document.createElement('style'));
styleTag.textContent = `.${className} { color: blue; }`;
<div>Some div</div>
With JS, you can write anything to the DOM, including a <style> tag. So for example:
const el = document.getElementById('changeColor');
el.onclick = function(e) {
const s = document.createElement('style');
s.innerHTML = '.box { background-color: yellow; }';
document.querySelector('body').appendChild(s);
}
.box {
width: 150px;
height: 150px;
background-color: red;
color: white;
padding: 20px;
}
#changeColor {
margin: 10px 0;
}
<body>
<button type="button" id="changeColor">Change It</button>
<div class="box">This is a box</div>
</body>
Add a CSS class inside styles tags
Use the DOMContentLoaded event to add a class to the element when the document is loaded
Get the elment through its tag name
Use setAttribute method in vanillaJS to add the CSS class to your tag elment
In this way it could be more maintainable yoru code, because you change at css level and JS auntomaticly will put the value tanken from css class declared
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Example</title>
<style>
.styles {
color: red;
}
</style>
</head>
<body>
<p>Hello there</p>
<script>
let paragraph = document.querySelector("p")
document.addEventListener("DOMContentLoaded", () => {
paragraph.setAttribute("class", "styles")
})
</script>
</body>
</html>

I want to be able to change each picture to appear in the same place on the screen every time i click a button

I am having some problems, the plan is when i click a button, the pictures change one bu one to represent a traffic light sequence. So when i run the code i want it to start on red and run through the sequence (British sequence). Although when i do run the code all i get is all the pictures coming up at the same time with no effect coming from the button. if anyone can help to accomplish this then that would be greatly appreciated! :)
Cheers!
Here is my code for HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Traffic Lights</title>
<link href="flag_style.css" rel="stylesheet" type="text/css">
<script src="flagscript.js"></script>
</head>
<body>
<input type="button" value="click me" onclick="changeLight()">
<img id="state_1" onclick="changeLight()" src="http://www.drivingtesttips.biz/images/traffic-light-red.jpg">
<img id="state_2" onclick="changeLight()" src="http://www.drivingtesttips.biz/images/traffic-lights-red-amber.jpg">
<img id="state_3" onclick="changeLight()" src="http://www.drivingtesttips.biz/images/traffic-lights-green.jpg">
<img id="state_3" onclick="changeLight()" src="https://assets.digital.cabinet-office.gov.uk/media/559fbe48ed915d1592000048/traffic-light-amber.jpg">
</body>
</html>
CSS:
.state_1 {
width:300px;
height:300px;
}
.state_2 {
width:300px;
height:300px;
}
.state_3 {
width:300px;
height:300px;
}
.state_4 {
width:300px;
height:300px;
}
JavaScript:
var flagSeq = ["state_1","state_2","state_3","state_4"];
var state = 0;
function changeFlag() {
if (state == 0) {
document.getElementById("state_1").className = flagSeq[state][0];
state++;
}
if else (state == 1) {
document.getElementById("state_2").className = flagSeq[state][1];
state++;
}
if else (state == 2) {
document.getElementById("state_3").className = flagSeq[state][2];
state++;
}
if else (state == 3) {
document.getElementById("state_4").className = flagSeq[state][3];
state = 0;
}
}
I deleted my other answer because this is apparently a homework problem. I'll gladly point out what to improve, though, so here's the first paragraph from the answer I posted.
There are several issues with your code, to the point where I wonder why you haven't noticed some of them yourself.
You seem to only want to show one image at a time, but you never actually hide any of them.
You're giving the images id attributes but only use class selectors in your CSS.
There are two elements with an id of state_3.
if else is not valid in JavaScript (the console will be happy to point out a syntax error). You probably meant to write else if instead.
As j08691 pointed out, you define a function changeFlag but refer to it as changeLight in your HTML.
Side note: for real-life projects, you'd be better off downloading the images and using those instead of linking to external resources.
What I would do is have only one img element and use JavaScript to change its src attribute.
What you want is something like this plunker
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Traffic Lights</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="script.js"></script>
</head>
<body>
<input type="button" value="click me" onclick="changeLight()">
<div id="light-div" class="light light-0" onclick="changeLight()"></div>
</body>
</html>
.light {
width: 300px;
height: 300px;
display: block;
background-position: center center;
background-repeat: no-repeat;
}
.light-0 {
background-image: url(http://www.drivingtesttips.biz/images/traffic-light-red.jpg);
}
.light-1 {
background-image: url(http://www.drivingtesttips.biz/images/traffic-lights-red-amber.jpg);
}
.light-2 {
background-image: url(http://www.drivingtesttips.biz/images/traffic-lights-green.jpg);
}
.light-3 {
background-image: url(http://assets.digital.cabinet-office.gov.uk/media/559fbe48ed915d1592000048/traffic-light-amber.jpg);
}
var lightSeq = ['light-0', 'light-1', 'light-2', 'light-3'];
var state = 0;
function changeLight() {
state++;
if (state === lightSeq.length)
state = 0;
document.getElementById('light-div').className = 'light ' + lightSeq[state];
}
Really there are a lot of errors in your code both HTML/JS, first hide something then better try to show it-
Still I got something for you, maybe this is what you needed, check the link below-
$(document).ready(function(e){
$('#ab').click(function(e){
//alert(1);
var a = document.getElementsByTagName('img');
for(i=1;i<=a.length;i++){
setTimeout(function(x){
return (function(){
$('img#state_'+x).show();
});
}(i),1000*i)
}
});
});
https://plnkr.co/XGG5PHI6bMP0XJ484rUS?p=preview

i'm having trouble turning 1 html file in 1 html 1 css and 1 js can some one give me a hand?

so i've started coding but i guess i'm dumb becuase i havan't been able to split this code i'd apreciate some help
<html>
<head>
<title>Exploring HTML</title>
<style>
body {
color: red;
}
h1 {
font-family: Arial, sans-serif;
font-size: 32px;
color: black;
}
</style>
</head>
<body>
<h1>My first web page</h1>
<p>This is my first web page, it's a little basic, but it's helping me understand how HTML works and how to markup my content.</p>
<button id="color">Change color!</button>
<script src="js.js">
</script>
</body>
</html>
This is how you can split up your webpage into different files. You want to use link in the head tag to include external CSS files. For external script files you still use the <script> tag but you don't insert any content to it, you apply the src attribute. <script> tags can be either in the head or the body tag, usually it's better to add it to the end of the body tag to prevent render blocking.
index.html
<html>
<head>
<title>Exploring HTML</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!-- Body Content -->
<div id="color">Click Here to Rotate Colors</div>
<script src="script.js"></script>
</body>
</html>
style.css
body {
color: red;
}
h1 {
font-family: Arial, sans-serif;
font-size: 32px;
color: black;
}
script.js
(function() {
// Set the variable "node" and set the event listener on click
var node = document.getElementById('color');
node.addEventListener('click',changeColor,false);
function changeColor(e) {
// Get the target (node) that the user clicked
var target = e.target || e.srcElement;
// Get the color from the data-color attribute
var color = target.getAttribute('data-color');
// Define the colors to rotate
var colors = ['red','green','blue'];
// Get the position of the color. red = 0, green = 1, etc
var index = colors.indexOf(color);
// If the index is the last item in the array you want
// to change the index to 0 otherwise it increases by 1
var next = (index+1 == colors.length ? 0 : index+1);
// Set the new color and the data-color attribute
target.style.color = colors[next];
target.setAttribute('data-color',colors[next]);
}
})();
A working example of the above code can be found at JSFiddle. The reason I'm setting data-color instead of reading the style.color variable is because I'm unsure if some browsers may modify this value in different ways. I know for a fact that the browser will not modify the data-color attribute.
these links should help you get an answer
http://www.w3schools.com/css/css_howto.asp
http://www.w3schools.com/js/js_whereto.asp

CSS transition with JavaScript

I'm trying to activate a CSS transition with Javascript through DOM when a div object is clicked. I avoided jQuery and used JS on purpose in order to learn DOM (this is actually my first experiment with it).
I implemented a standard solution: getting the elements' ListNode from the HTML document, then changing the className of the desired object. Yet, it does not seem to work properly
(I'm obviously using Firefox).
Thank you in advance.
Here are the files.
<!doctype html>
<html>
<head>
<link rel = stylesheet href = "style.css" type = "text/css" media = screen>
<script src = "script.js" type = "text/javascript"></script>
</head>
<body>
<div class = "image" onclick = "foo()"></div>
</body>
</html>
style.css
.transition {
-moz-transition: 2s width;
width: 150px;
height: 100px;
}
.image {
-moz-transition: 2s width;
width: 100px;
height: 100px;
background-color: black;
}
script.js
function foo() {
var k = document.getElementsByClassName("image");
k[0].className = "transition";
}
EDIT: Edited the code in order to make immediately visible the working solution.
You're using getElementsByName, but you don't have an element with a name of image, instead you have an element with a class of image. You probably intended to use document.getElementsByClassName('image'). On a side note, the structure of your html page is incomplete, you need a <head> and <body> section, also your <html> opening tag is in the wrong place.
<!doctype html>
<html>
<head>
<link rel = stylesheet href = "style.css" type = "text/css" media = screen>
<script src = "script.js" type = "text/javascript"></script>
</head>
<body>
<div class = "image" onclick = "foo()"></div>
</body>
</html>
Try this in your javascript logic:
function foo() {
var k = document.getElementsByClassName("image");
k[0].className = "transition";
}​
As Stencil mentioned everything should be inside HTML Tag.Similar kind of width animation could be easily achieved using jQUery
$('.image').animate({width: 250}, 500 );

Categories