Apply Css Animation to a class with onclick Using JavaScript - 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>

Related

How to apply a class to elements based on their z-Index value? (using javascript)

I'm trying to change the opacity of all elements on my document, except for the one I clicked (which has the highest z-Index).
Here is the code I'm using, am I accessing the z-Index's wrongly? When run, the opacity of the whole page changes (including those with a z-Index higher than 6).
allElements = document.getElementsByTagName("*")
for (let i = 0; i < allElements.length; i++) {
if (allElements[i].style.zIndex < 6)
allElements[i].style.opacity='0.7'
}
I would suggest a cleaner and more robust approach based on classes.
Basically use event listeners and toggle classes on your body and your highlightable items. The rest is just CSS as you would imagine.
resetAllHighlights = () => [...document.querySelectorAll('.item')].map(e => e.classList.remove('highlighted'));
toggleHighlightMode = (highlightMode) => {
if (highlightMode) document.querySelector('body').classList.add("highlight-enabled");
else document.querySelector('body').classList.remove("highlight-enabled");
return highlightMode = !highlightMode;
};
[...document.querySelectorAll('.item')].map(e => e.addEventListener('click', (e) => {
resetAllHighlights()
toggleHighlightMode(true)
e.currentTarget.classList.add('highlighted');
}));
.item {
height:100px;
width: 100px;
background-color: red;
margin: 5px;
opacity: 1;
}
body {
display: flex;
}
body.highlight-enabled .item:not(.highlighted) {
opacity: 0.5;
}
<body class="">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</body>
When you access an element's .style property, you will only have access to the styles that were established on the element via the HTML style attribute. If the styling was done via the class attribute or set with JavaScript, the .style property won't be able to access it. In those cases, you must use .getComputedStyle(), which doesn't care how or where the styling was set.
And speaking of how to set styles, it's always better to set styles using pre-made CSS classes and then just add or remove the class(es) as needed instead of setting individual styles. Using classes reduces duplication of code, is easier to manage, and scales better. You can easily access and add, remove or toggle classes with the .classList API.
Also (FYI), don't use .getElementsByTagName() as this is a legacy method that returns a "live node list", which can hurt performance. Instead, use .querySelectorAll()
So, here's an example similar to what you are doing:
let divs = document.querySelectorAll("div.opaque");
// Just set up one event handler at a common ancestor of
// all the elements that may trigger the event
document.addEventListener("click", function(event){
// Check to see if the event was triggered by
// an element you care to handle
if(event.target.classList.contains("opaque")){
// Loop over all the necessary elements
divs.forEach(function(div){
// Check the z-index using .getComputedStyle()
if(getComputedStyle(div).zIndex < 6){
// Instead of modifying a style directly,
// just add a pre-made class
div.classList.add("lightOpaque");
}
});
}
});
body { background-color: red; }
div { height:35px; border:1px dotted grey; position:relative; z-index:5; background-color:skyblue; }
.lightOpaque { opacity: .7; }
.special { position:relative; z-index:7; background-color:aliceblue; }
<div class="opaque">
</div>
<div class="opaque">
</div>
<div class="opaque special">
</div>
<div class="opaque">
</div>
<div class="opaque">
</div>
<div class="opaque">
</div>

Animate text using intervals (and timeouts?) Javascript, JQuery

I would like to make a Text run from left to right in a loop. Here is the fiddle with my attempt:
https://jsfiddle.net/9Lruxym8/33/
I started with css #keyframes but I think I need the width of the text itself if I want the text to run seamlessly. My idea was to write down the text two times and once the div with the texts has run exactly halfway, the animation starts again.
After #keyframes didn't work, I tried jQuery animation. It did work somewhat but didn't run smoothly. Now I'd like to do it via transition. I thought a combination of intervals and timeouts could do the trick but I still don't get it to work - and now, I don't know why. Does anyone have a hit for me?
function runText() {
var text_width = $('#runningP').width()/2;
console.log(text_width)
setInterval(function(){
console.log("interval");
$('.text').css({'transition':'margin-left 5s'});
$('.text').css({'margin-left':'-' + text_width + 'px'});
moveBack();
}, 3000);
function moveBack() {
console.log("timeout")
setTimeout(function(){
$('.text').css({'transition':'none'});
$('.text').css({'margin-left': 0});
}, 3000);
}
}
runText();
I've recently made a bit of custom code for this functionality.
Looking at my code, it seems a bit much having essentially 3 "levels" (.scrollTextWrap > .scrollingText > .scrollContent) but this was the structure I ended up using to get a clean and consistent effect.
I've added in an initialiser too so that you could simply add the scrollMe class and have them setup the html for you
In the snippet I've added a .parentContainer purely to show how it works when constrained
$(document)
.ready(function(){
// check that scrollingText has 2 scrollContent element
$('.scrollMe')
.each(function(){
initScrollingText($(this));
});
});
function initScrollingText($this){
// store text
var text = $this.text();
// empty element
$this.html(null);
var $wrap = $('<div class="scrollTextWrap" />'),
$text = $('<div class="scrollingText" />'),
$content = $('<div class="scrollContent" />');
// set content value
$content.text(text);
// duplicate content
$text
.append($content)
.append($content.clone());
// append text to wrap
$wrap.append($text)
// add $wrap to DOM
$wrap.insertAfter($this);
// remove old element
$this.remove();
}
/* to simulate width constraints */
.parentContainer {
width: 140px;
position:relative;
overflow:hidden;
}
.scrollTextWrap {
position:relative;
width:auto;
display:inline-block;
}
.scrollingText {
display: flex;
position:relative;
transition:left 0.1s;
animation: scrollText 5s infinite linear;
}
.scrollContent {
white-space: nowrap;
padding-right:5px;
}
#keyframes scrollText {
0% { left:0 }
100% { left:-50% }
}
<div class="parentContainer">
<div class="scrollMe">Content you want to scroll goes here</div>
<!-- alternatively you can just structure the html -->
<div class="scrollTextWrap">
<div class="scrollingText">
<div class="scrollContent">Content you want to scroll goes here</div>
<div class="scrollContent">Content you want to scroll goes here</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

workaround for display block and css transitions work properly

CSS transitions will not apply if you set the display property of an element to block immediately before changing the property with the transition attached. You can see the issue in the following example:
var dom = {};
dom.creative = document.getElementById('creative');
dom.creative.style.display = 'block';
dom.creative.style.opacity = 1;
#creative {
display: none;
opacity: 0;
transition: opacity 2s;
}
<div id="creative">
<span>Sample text</span>
</div>
The issue can be fixed by forcing a repaint on the element:
var dom = {};
dom.creative = document.getElementById('creative');
dom.creative.style.display = 'block';
var a = dom.creative.offsetHeight; /* <-- forces repaint */
dom.creative.style.opacity = 1;
#creative {
display: none;
opacity: 0;
transition: opacity 2s;
}
<div id="creative">
<span>Sample text</span>
</div>
This solution is not good because it adds the need of a non intuitive extra line of code everytime you need the display transition combination.
A SO user found an elegant solution (https://stackoverflow.com/a/38210213/6004250) to this problem replacing the transition by the animation property. I'm still curious about making it work together with CSS transitions (because they are easier to understand and to use). Any ideas?

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

change css onload with 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.

Categories

Resources