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 );
Related
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>
i am a newbee so sorry if my question is basic.
i have written a code (with the help of the forum offcourse) where by clicking on an image another one appears and when you click on the new one, again another one appears and so on.
the problem is i can not add an style to the code and make the images appear in different positions to make a layout.
can anyone here help me?
thank you so much
<meta charset="utf-8">
<title> COOPER BLACK </title>
<link rel="stylesheet" type="text/javascript" href="style.css" media="screen">
</head>
<div class="container">
<script type="text/javaSCRIPT">
var i = 1
function imageClick() {
if (! this.alreadyClicked)
{
addimage();
counter();
this.alreadyClicked = true;
}
}
function addimage() {
var img = document.createElement("img");
img.src = "images/d"+i+".jpg";
img.onclick = imageClick;
document.body.appendChild(img);
}
function counter() {
i = i + 1
}
</script>
<div class="first">
<input class="first" type="image" src="images/d0.jpg" onclick="imageClick();">
</div>
</div>
Try setting the class attribute this way
img.setAttribute("class", "YourClassName");
Then apply the style to YourClassName in a CSS file/style tag. (Might also want to call the script after you load the CSS) Like so
.YourClassName { /* style here */ }
Edit:
You can also check if the elements are rendered well (the HTML tags have the class names and onClick methods) using the console (press F12 on the page)
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
IE (tested 7-10) is not applying the base (an absolute URL) to background images within a style tag, resulting in 404. This only happens when the code is injected using innerHTML (a requirement of the larger application this belongs to). It applies the base to all other elements as seen in the example.
Any suggestions?
Edit 2014/01/13 This is fixed if I remove the style tags from the HTML string and manually append them to the header. Would like to know if this is the only answer. Based upon this solution: How to create a <style> tag with Javascript
<!DOCTYPE html>
<html>
<head>
<title>base test</title>
<base href="http://absoluteurl.com/">
</head>
<body>
<div id="container"></div>
</body>
<script>
var html = "First Node<br>Second Node.<br><style>#bkgdiv {background-image: url(media/ex_amp.jpg); border: 1px solid #f00; width: 200px; height: 200px;}</style><div id=\"bkgdiv\">DIV w/ Background</div><br><img src=\"media/ex_amp.jpg\">";
document.getElementById('container').innerHTML = html;
</script>
</html>
Have you tried the jQuery appendTo method?
Inline style elements have to be removed from the HTML string, added to a style element object, and then appended to the head.
<!DOCTYPE html>
<html>
<head>
<title>base test</title>
<base href="http://absoluteurl.com/">
</head>
<body>
<div id="container"></div>
</body>
<script>
var html = "First Node<br>Second Node.<br><style>#bkgdiv {background-image: url(media/ex_amp.jpg); border: 1px solid #f00; width: 200px; height: 200px;}</style><div id=\"bkgdiv\">DIV w/ Background</div><br><img src=\"media/ex_amp.jpg\">";
var head = document.getElementsByName('head')[0];
content.html = content.html.replace(/<style(.|\n)*?>(.|\n)*?<\/style>/ig, function(match) {
var css = match.replace(/<\/?style(.|\n)*?>/ig, "");
style = document.createElement('style');
style.type = 'text/css';
if(style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
return "";
});
document.getElementById('container').innerHTML = html;
</script>
</html>
I have successfully created an Ace editor before, but recently I am making a website called CodeProjects, and I want to put an Ace editor in. Whenever I try, it only shows the text function foo(items) {
var x = "All this is syntax highlighted";
return x;
}. On the page http://ace.c9.io/#nav=embedding&api=ace, it says you only need the code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>ACE in Action</title>
<style type="text/css" media="screen">
#editor {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
</style>
</head>
<body>
<div id="editor">function foo(items) {
var x = "All this is syntax highlighted";
return x;
}
</div>
<script src="/ace-builds/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/javascript");
</script>
</body>
but when I try to embed it (or even just make the editor, not the site), again, it only shows function foo(items) { var x = "All this is syntax highlighted"; return x; }
Any suggestions?
it also says to copy files into your project. If you don't want to do that, include script from cdn
<script src="//cdn.jsdelivr.net/ace/1.1.01/min/ace.js"
type="text/javascript" charset="utf-8"></script>
see http://jsbin.com/ojijeb/165/edit
You need to put the content outside of the editor div [or fetch the content on page load using AJAX]. Either way, you then load the content into the editor with JavaScript: editor.setValue("hello world");.
To set the height of the editor, you resize the div it lives in, then call the editor's resize method.
var div = document.getElementById('editor');
div.style.height = some_multiple_of_the_line_height_for_tidiness;
editor.resize();
In my experience, you need to change div to pre. Just using pre instead of div in following way should solve your problem.
<pre id="editor" >
</pre>