change css onload with javascript - javascript

It's a simple javascript command to get the classname to change when the page loads. What am I doing wrong that it isn't working? http://jsfiddle.net/wtH2Y/4/
<html>
<head>
<style>
.away {
margin: 30px 0 0 0 !important;
position:fixed;
-webkit-transition: margin 0.6s;
-moz-transition: margin 0.6s;
-o-transition: margin 0.6s;
}
.in {
margin:0;
position:absolute;
}
</style>
<script>
window.onload = function pre-loader() {
document.getElementByClassName('away').className = 'in';
};
</script>
</head>
<div class="away">
this should slide up when the page loads
</div>

A few things:
Function names cannot have dashes in them. Rename your function.
If you're using a named function, I wouldn't assign it to a property this way. Either make it anonymous or assign it like so:
function foo() {
...
}
window.onload = foo;
Otherwise, you won't be able to call foo().
getElementByClassName should be getElementsByClassName (notice the s). Also, since it'll return a collection of elements, you will need to iterate over it with a for loop.

Because the function is document.getElementsByClassName and not document.getElementByClassName. It returns an Array. So you need to get the first element and apply the class. Like this...
document.getElementsByClassName('away')[0].className = 'in';
To make it simple, why don't you assign an id to the div
<div class="away" id="mydiv">
and then use document.getElementById. Like this...
document.getElementById('mydiv').className = 'in';
It is much simpler and easy to use.

Related

How do I connect html transforms in multiple classes? [duplicate]

This question already has answers here:
How can I apply multiple transform declarations to one element?
(5 answers)
How to have multiple CSS transitions on an element?
(9 answers)
Closed 2 years ago.
I'm trying to use multiple transforms in a single element so that the end product is a combination of all of the transformations applied together.
However, the only one transform property will be ignored when there are multiple of them.
Say, if I want a div transformed by rotate(20deg) and skewY(20deg), this wouldn't work:
.foo {
transform: rotate(20deg);
}
.bar {
transform: skewY(20deg);
}
<div class="foo bar"></div>
Only one will be applied. Although compounding the transformations could work, it would be impractical as there can be potentially many combinations to the transformations. Rather than doing this:
.one-one {transform: rotate(10deg) skewY(1deg);}
.one-two {transform: rotate(10deg) skewY(2deg);}
.one-three {transform: rotate(10deg) skewY(3deg);}
.one-four {transform: rotate(10deg) skewY(4deg);}
.two-one etc.
I want to do this, so that i can apply the transformations on button clicks, rather than to exhaust all possible combinations of the transformations:
.one {transform: rotate(10deg);}
.two {transform: rotate(20deg);}
.three {transform: rotate(30deg);}
.four {transform: rotate(40deg);}
.uno {transform: skewY(10deg);}
.dos {transform: skewY(20deg);}
.tres {transform: skewY(30deg);}
Current solutions I think are possible:
There is a way to add to the transform property of a <div>
Somehow modify classes in some way
Changing the CSS using jQuery, but it seems like this will also overwrite the property with css() rather than adding to the transform style
I'd prefer css/js solutions, but jQuery answers are welcome too, I'm just not familiar with it.
You may look at CSS var(--X) (see links below snippet's demo) and , set all transformation you intend to 0 by default and update them via the className :(mind support before use : https://caniuse.com/#feat=mdn-css_properties_custom-property_var and eventually a polyfill https://github.com/nuxodin/ie11CustomProperties )
possible exemple without JavaScript https://codepen.io/gc-nomade/pen/RwWLOWr :
.foo {
--rotate: 20deg;
}
.bar {
--skewY: 20deg;
}
div[class] {
transform: rotate( var(--rotate, 0)) skewY( var(--skewY, 0));/* fallback value is here 0 */
}
/* demo purpose */
div[class] {
float: left;
border: solid;
}
html {
display: flex;
height: 100%;
}
body {
margin: auto;
}
<div class="foo bar">foo bar</div>
<div class="foo ">foo</div>
<div class="bar">bar</div>
<div class="nop">no transform</div>
https://developer.mozilla.org/en-US/docs/Web/CSS/--*
Property names that are prefixed with --, like --example-name, represent custom properties that contain a value that can be used in other declarations using the var() function.
Custom properties are scoped to the element(s) they are declared on, and participate in the cascade: the value of such a custom property is that from the declaration decided by the cascading algorithm.
Fallback : https://drafts.csswg.org/css-variables/#example-abd63bac
Note: The syntax of the fallback, like that of custom properties, allows commas. For example, var(--foo, red, blue) defines a fallback of red, blue; that is, anything between the first comma and the end of the function is considered a fallback value.
if supports comes a question, you may look at : IE11 - does a polyfill / script exist for CSS variables?
There's many ways you can approach that. How about this below?
I have created two ` to read the values for skew and rotation and them apply the effects.
Remember it doesn't matter where the values come from. They can be hard-coded in your buttons as data-* attributes(if you want them fixed). This is just to show you how you can approach it with javascript( Ihave added some commends to make it simpler to understand):
var object = document.querySelector(".shape");
// this function takes care of Rotational effect
function rotate(event)
{
var rotation_val = document.getElementById("rotationVal").value;
// this get's the css transform expression for rotation which is
// stored as data-attribute on every button, because it tells you what button is resposible for what transformation. But you can store this anywhere you want.
var css_transform = event.currentTarget.getAttribute("data-rotation");
// this here just replaces say rotate(_r_) to rotate(15deg) if val was 15
var effect = css_transform.replace("_r_",rotation_val + "deg");
// Take not of this. ere I am not overriding the transform property. Instead
// I am adding a transformation to it. more like compounding but dynamically.
object.style.transform += effect;
}
// this function takes care of Skewing effect
function skewY(event)
{
var skew_val = document.getElementById("skewVal").value;
var css_transform = event.currentTarget.getAttribute("data-skew");
var effect = css_transform.replace("_s_",skew_val + "deg");
object.style.transform += effect;
}
function apply_all(){
var buttons = document.querySelectorAll(".effect_button");
buttons.forEach( function(button){
button.click();
});
}
.container{
padding: 60px;
border: thin solid #dbdbdb;
}
.shape{
width: 60px;
height: 60px;
background-color: green;
}
<div class="container">
<div class="shape">
</div>
</div>
<input id="rotationVal" />
<button class="effect_button" data-rotation="rotate(_r_)" onClick="rotate(event)">rotate</button>
<br />
<input id="skewVal" />
<button class="effect_button" data-skew="skewY(_s_)" onClick="skewY(event)">Skew</button>
<br />
Or Rotate and Skew at the same time:
<button onClick="apply_all(event)">Transform</button>

CSS Opacity transition not affecting child elements

I have an Opacity transition affecting a div element but it does not seem to change the opacity of the child elements inside the div. My understanding is that the property of the containing div should apply to all child elements as well.
Any help would be greatly appreciated. Below is the HTML and CSS:
.tabtext {
opacity: 0;
transition: opacity 1s;
}
<div id="smartITtext" class="tabtext">
<h2 class="tabtext">Some Text</h2>
</div>
Below is the line in Javascript which changes the Opacity:
document.getElementById(smartITtext).style.opacity= 1;
When applying your javascript code it will add the opacity style on the element in your html. So it doesn't overwrite the css style.
Here is an example on how you could let it work.
document.getElementById("btn").addEventListener("click",function(){
var div = document.getElementById("smartITtext");
div.style.opacity = 0.5;
});
.tabtext {
transition: opacity 1s;
}
<div id="smartITtext" class="tabtext">
<h2 class="tabtext">Some Text</h2>
</div>
<input type="button" id="btn" value="change opacity" />
Your child element has a specific opacity set on it. Therefore, it won't inherit any changes you make to the parent and your transition won't run: you've told it to have opacity: 0;, so that's what it will have despite whatever you set the parent element's opacity to.
That's equivalent to setting the color of a child element to be blue and setting its parent's color to red: that child element will still have blue text as you've explicitly told it to.
You will need to change that specific element's opacity to run your transition. Judging by your code, something like:
document.getElementById(text).firstElementChild.style.opacity = 1;
or
document.querySelector('#' + text + ' .tabText').style.opacity = 1;
would do the trick for you.
Firstly your javascript refences an id that does not match your html.
Secondly the id reference ("text") needs to be in quotes.
Here is an alternative way to get the desired result.
document.getElementById("smartITtext").className += " Active";
.tabtext {
opacity: 0;
transition: opacity 1s;
}
.tabtext.Active{
opacity:1;
}
<div id="smartITtext" class="tabtext">
<h2 class="tabtext">Some Text</h2>
</div>
The property of the parent element should apply to the child element. UNLESS the child element has it's own property.
So if we have this code:
#container {
color: blue;
}
.one {
color: firebrick;
}
<div id="container">
<span class="one">hello </span>
<span class="two">World</span>
<span>. <-- hello should be red, while world and this text should be blue</span>
</div>
play in jsbin: https://jsbin.com/focimuk/edit?html,css,output
So for a solution, try setting just opacity on the parent element, and add a transition to it.

Apply Css Animation to a class with onclick Using JavaScript

I have a this script :
function ani(){
document.getElementById('para').className ='exeInputapparition';
}
To apply a css animation on my element who has the ID para.
It's working but i wanted to know if it's possible to apply to all element who have the class para instead of the ID because i have more than one element where i need to apply my CSS animation.
Thanks in Advance for your help :)
The Css :
#keyframes inputapparition {
0%
{
opacity: 0;
}
100%
{
opacity: 1;
}
}
.exeInputapparition
{
animation-name: inputapparition;
animation-duration: 0.5s;
animation-fill-mode: forwards;
}
#para
{
margin: 0;
font-family: "Roboto"
font-size: 20px;
opacity: 0;
}
The function querySelectorAll returns all elements, it's a "DOM array", therefore there isn't the attribute className. You should loop the list and change one by one:
var allElementsPara = document.querySelectorAll(".para");
for (var i = allElementsPara.length - 1; i >= 0; i--) {
allElementsPara.item(i).classList.add("exeInputapparition");
};
You can use document.querySelectorAll
var x=document.querySelectorAll(".para");
for(var a =0;a<x.length;a++){
x[a].classList.add("exeInputapparition")
}
JSFIDDLE
JSFIDDLE WITH .para
The id is unique. You must use a same class for all element that you want to animate. For all element, put the class animate and edit the function
function ani(){
document.getElementsByClassName('animate').className ='exeInputapparition';
}
A more performing solution would be to apply the class to the body element.
Every access to the DOM takes some ms and when your web page becomes huge, with a lot of JavaScript, it can get slow.
Accessing a single DOM element (<body>) instead N elements with the given class will:
reduce the number of accesses to the DOM;
reduce to 0 the queries you perform on the DOM;
make sure all the elements starts appearing at the same time;
assure that every element with the class para added after the script has run, will have the correct style;
// here I use a `setTimeout` to make the function start automatically
// logically you can take the content of this function and put it
// wherever you prefer
setTimeout(function() {
document.body.className += ' in';
}, 1000);
.para {
opacity: 0;
transition: opacity 0.5s linear;
}
.in .para {
opacity: 1;
}
<div class="para">para 1</div>
<div class="para">para 2</div>
<div class="para">para 3</div>
You can disregard the previous answers, people did and could not know what exactly you want before you posted the css.
You do not the keyframes for this.
Here is a full JS solution, as you need JS for this anyway.
document.querySelector(".reveal3").addEventListener("click", function(){
toggle();
});
function toggle(){
var c = document.querySelector(".reveal3");
if(c.style.opacity == 1){
c.style.opacity = 0;
} else {
c.style.right = "0px";
c.style.opacity = 1;
}
}
See it in action here, the div on the right side, click on it to toggle visibility.
http://codepen.io/damianocel/pen/GopoJB
this solution will help your.it is easy to use jquery with this.I have implemented for a div.you can use it for image also.so try this
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div class="clickme" style="background-color:orange;width:100px;height:100px;">
<!--use <img src="imageurl"/> here-->
</div>
<!-- js-->
<script type="text/javascript">
$(document).ready(function(){
$(".clickme").click(function(){
$(this).animate({opacity:0.5},1000);
});
});
</script>
</body>
</html>

jQuery - how to remove a class from an element with a given delay?

When a user updates a record in the database, I'll modify the record using an AJAX request. Then, I add to the rendered div a class by calling the addClass method. The class I add (let's call the class colored) to the div contains only a background color directive (to highlight the current modified record).
So far so good.
Now I want to remove this class with a fadeOut effect, after 1 second.
I've tried these approaches, but in both cases it's not only removing the class but the whole div.
$("#id1").fadeOut(1000, function() {
$(this).removeClass('colored');
});
or
$("#id1").delay(1000).fadeOut().removeClass('updated_item');
Why is the div removed instead of the class ? Actually, the div is getting a display: none; style - I see this in the console.
fadeOut will fade the entire element out and hide it from the screen. If you want to fade the effects of the class, you can use jQuery UI .removeClass() (which accepts a time duration and fade effect, unlike regular jQuery) or CSS3 transitions.
You can use setTimeout function like this:
setTimeout(
function(){
$("#id1").removeClass('updated_item');
}
,1000 //1 second
)
And if you want to change the color with animation you can just add a transition style in your CSS like this:
.myDiv{
background:red;
transition:background 1s;
-webkit-transition:background 1s;
}
.colored
{
background:blue;
}
I dont know if I got it, is this what you want ?
Fiddle
jQuery('.action').click(function() {
jQuery(this).parent().addClass('highlight');
if ( confirm('Are you sure?') ) {
jQuery(this).parent().fadeOut(1000, function() {
jQuery(this).addClass('remove').removeClass('highlight');
});
} else {
jQuery(this).parent().removeClass('highlight');
}
});
.highlight {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
#1 Click me
</div>
<div>
#2 Click me
</div>
You're applying the fadeOut function to the div itself, not on the class:
//the div, will fadeout after 1000 ms and get the class removed
$("#id1").delay(1000).fadeOut().removeClass('updated_item');
If you want to remove the background-color with a fading effect, you'd have to use something like:
setTimeout(function() {
$('#id1').removeClass('updated_item');
}, 1000)
On the css side, use a transition for the fadeOut effect:
#id1 {
transition: background-color 0.5s ease;
}
.updated_item {
background-color: yellow;
}
Fiddle

Javascript Function for mouse events

I am trying to change the following code so that instead of having to click-and-hold the linked image to make it bigger (150 into 300), I could click it once to make the image bigger, and click it again to make the image return to smaller. I have to do this with multiple images on the page. (Be forewarned, I do not really understand jquery and have a very basic understanding of javascript. But I'm learning!)
function Down(sender)
{ var thisWidth=parseInt(sender.style.width.replace('px',''));
sender.style.width=(300) + 'px';}
function Up(sender)
{ var thisWidth=parseInt(sender.style.width.replace('px',''));
sender.style.width=(150) + 'px';}'
<img src="picture.jpg" onmousedown="Down(this)" onmouseup="Up(this)" />
You could toggle a class.
Firstly, you should set a class to target specific element(s) and setting width attribute is preferred method:
<img class="imgToggling" src="picture.jpg" width="150">
Now, set relevant CSS for a big class:
.big {
width: 300px;
}
Then on click, toggle this class, binding event using jQuery (preferred over inline scripting):
$(function () { //shorthand for document ready handler
$('.imgToggling').on('click', function () {
$(this).toggleClass('big');
});
});
-DEMO-
If you wish to get some kind of transition, add this CSS rule e.g:
img.imgToggling {
-webkit-transition: width 1s ease-in-out;
-moz-transition: width 1s ease-in-out;
-o-transition: width 1s ease-in-out;
transition: width 1s ease-in-out;
}
-DEMO with transition-
I have to do this with multiple images on the page.
Then you can do this with jQuery (as jQuery is tagged):
$('img').on('click', function(){
var thisWidth=$(this).width(),
setWidth = thisWidth >= 300 ? 150 : 300;
$(this).width(setWidth);
});
assumed if images are not dynamically generated or placed with ajax in the dom.

Categories

Resources