Translate jQuery click(), hide() and fadeIn() to native JS - javascript

So, I'm trying hard to speed up my page (by avoiding some requests) and wonder if anyone knows how to keep the following code working without having to load the whole JQuery library:
$("#div1").click(function () {
$("#div2).hide();
$("#div3").fadeIn();
})
Ofcourse this code needs a JQuery library to work, but it's heavier than my page itself.
Is there a way,somewhere, to just select the code needed from the library and insert it inline (in my html)?
Thank You,

CSS3 #keyframes is a clean way to do what you want without jQuery. Have a look at this thread, which has a demo. It actually runs smoother than jQuery's fadeIn.

Here's an example using CSS for the fade and plain Javascript for triggering the changes:
document.getElementById('div1').onmousedown = function() {
addClass('div2', 'hide');
addClass('div3', 'show');
}
function addClass(id, className) {
var el = document.getElementById(id);
if (el.classList)
el.classList.add(className);
else
el.className += ' ' + className;
}
#div2.hide {
display: none;
}
#div3 {
opacity: 0;
transition: 0.3s opacity ease;
}
#div3.show {
opacity: 1;
}
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>

If you aren't set on using jQuery you could just use normal JS, something along these lines:
document.getElementById('div1').onclick(function() {
document.getElementById('div2').style.visibility = 'hidden';
document.getElementById('div3').style.visibility = 'visible';
});
disclaimer there are better ways to do these DOM manipulations, this is an example!

The fadeIn function taken from here.
function fadeIn(el) {
el.style.opacity = 0;
var tick = function() {
el.style.opacity = +el.style.opacity + 0.01;
if (+el.style.opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16)
}
};
tick();
}
document.getElementById("div1").onmousedown = function () {
document.getElementById("div2").style.display = 'none';
fadeIn(document.getElementById("div3"));
};

This only works on single selectors and not multiple elements at once, and it's not going to work for any other jQuery functions. For your situation it will allow a drop in replacement so you don't require an extra library.
$ = function(selector) {
return document.querySelector(selector);
}
HTMLElement.prototype.hide = function() {
this.style.visibility = "hidden";
this.style.opacity = 0;
}
HTMLElement.prototype.fadeIn = function() {
this.style.display = "block";
this.style.visibility = "visible";
this.style.opacity = 1;
}
For the fadeIn() animation you can add a CSS property to your element. This is set to 400ms just like jQuery's effect:
transition: opacity .4s ease;

Related

Pure JavaScript fadeout then load

I have a fairly simple jQuery snippet that fades out an element then loads an external PHP page via AJAX after a button is clicked, and I'm trying to do the same thing using Javascript, so I can avoid using jQuery at all.
jQuery:
$(document).on("click", "#button", function () {
$("#image").fadeOut(580, function () {
$("#image-wrapper").load("loader.php");
});
return false;
});
Javascript:
document.getElementById("button").addEventListener("click", function () {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
document.getElementById("image").classList.add("fade--out");
document.getElementById("image-wrapper").innerHTML = xhr.responseText;
console.log("Success");
} else {
console.log('Error');
}
};
xhr.open('GET', 'loader.php');
xhr.send();
});
And some CSS:
.fade--out {
opacity: 0;
}
#image {
transition: opacity 480ms ease 0s;
}
So far I have written that but I can only get the XMLHttpRequest to work ok but I can't seem to get the image element to fade out before loading the PHP file. How can I get the image div to fade out then load the PHP file inside the imaga-wrapper div?
See comments:
document.addEventListener("click", function (evt) {
// Because of event delegation, we need to check to see
// if the source of the event was the button
if(evt.target.id === "button"){
// Add a class to the image that changes the opacity to fully
// transparent, but because of the default image styling, a
// CSS transition will do that over the course of 480 milliseconds.
document.getElementById("image").classList.add("fade--out");
// Once that is done, call the supplied function
requestAnimationFrame(function(){
// AJAX Call here
});
}
});
.fade--out {
opacity: 0;
}
#image {
transition: opacity 480ms ease 0s;
}

How to Fade Out an element using Javascript

I have a loading page that I used javascript to make. I would like to be able to fade-out the loading page as the index.html fades in. I understand this can easily be done with jQuery, but would like to not use jQuery since I have yet to use it on this site. I understand this may be a common question, but I have not been able to tailor other answers to my solution since most use jQuery.
I am thinking to edit the opacity of the loading element onReady. Or could I do this with simple CSS?
Javascript:
function onReady(callback) {
var intervalID = window.setInterval(checkReady, 1000);
function checkReady() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}
}
function show(id, value) {
document.getElementById(id).style.display = value ? 'block' : 'none';
}
onReady(function () {
show('page', true);
show('loading', false);
});
HTML:
<div id="loading">
<div class="logo">
Logo
</div>
<span class="loading-center-cross"></span>
<h3>Loading...</h3>
</div>
<div id="page">
.....
</div>
I expect for the loading screen to fade to the index.html as previously described. Thanks for all the help!
You can do this with CSS, using something like the following:
function onReady(callback) {
var intervalID = window.setInterval(checkReady, 1000);
function checkReady() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}
}
function show(id, value) {
document.getElementById(id).classList.toggle('fade-in-out', value);
}
onReady(function () {
show('page', true);
show('loading', false);
});
And have the following CSS:
#page,
#loading {
transition: opacity 1s;
}
.fade-in-out {
opacity: 0;
pointer-events: none;
}
That way, the show() function will toggle a class of fade-in-out based on value, and there will be a transition to 'fade' the div in and out, with an addition of pointer-events: none to make the div non-interactive whist transitioning.

pause and resume setInterval in javascript

I am trying to mimic the typing effect on the codility's home page in JavaScript.I have already achieved the typing and deleting effect
using setInterval().
Here's the jsfiddle of that:
https://jsfiddle.net/yzfb8zow/
var span=document.getElementById("content");
var strings=["hello world","how r u??"];
var index=0; //get string in the strings array
var chIndex=0; //get char in string
var type=true;
setInterval(function(){
if(index===strings.length)
index=0;
if(type){
typeIt();
}
else
deleteIt();
},200);
// type the string
function typeIt(){
if(chIndex<strings[index].length)
span.innerHTML=strings[index].substring(0,chIndex++);
else
type=false;
}
//delete the string
function deleteIt(){
if(chIndex===0){
index++;
type=true;
}
else
span.innerHTML=strings[index].substring(0,chIndex--);
}
the html
<span id="content"></span>
<span id="cursor">|</span>
the css
#cursor{
-webkit-animation: 1s blink step-end infinite;
-moz-animation: 1s blink step-end infinite;
animation: 1s blink step-end infinite;
}
#keyframes blink {
from, to {
opacity:0;
}
50% {
opacity: 1;
}
}
#-moz-keyframes blink {
from, to {
opacity:0;
}
50% {
opacity:1;
}
}
#-webkit-keyframes blink {
from, to {
opacity:0;
}
50% {
opacity:1;
}
}
What I can't get my head around is how could I pause the setInterval function at the beginning of string change and at the end to get a clear blinking cursor.
I have looked up other answers Pause and resume setInterval and How do I stop a window.setInterval in javascript? but I am unable to comprehend how to use it in this context.
Also it would be great if you could tell me how to improve my code.
I edited your code here is your jsfiddle back: https://jsfiddle.net/yzfb8zow/5/
Also a little code explanation
var typingFunction = function() {
if (index === strings.length) {
index = 0;
}
if (type) {
typeIt();
} else {
deleteIt();
}
}
I declared your previous typing function to later be able to use it as desired.
var x = setInterval(typingFunction.bind(typingFunction), 200);
Stored the interval so I can clear it later - stored in a global variable (not necessarily ok and there are other solutions but store it).
function typeIt() {
if (chIndex == -1) {
chIndex += 1;
clearAndRestartInterval(1000);
return;
}
if (chIndex <= strings[index].length) {
span.innerHTML = strings[index].substring(0, chIndex++);
} else {
clearAndRestartInterval(1000);
type = false;
return;
}
}
In the typeIt function I clear interval at the begining at chIndex = -1, wait a while so letting the cursor blink before I restart the interval. Than I clear it again at the end of the string. My chIndex starts from -1 so I know when to blink at the begining.
Rest of the code is self explanatory.
Feel free to edit the parameter of the clearAndRestartInterval function in order to set the time of the blinking at the begining and the end.
function clearAndRestartInterval(timeOfRestart) {
clearInterval(x);
setTimeout(function() {
x = setInterval(typingFunction.bind(typingFunction), 200);
}, timeOfRestart);
}
Last but not least the stop and restart function of the interval. This is quite simple and x - is the previously declared setInterval - globally which I clear and reset with a new interval ofter some time.
Hope this helps.
Cheers
You will have to use nested timeouts.
Call typeIt directly, as its a default action.
In typeIt, add a setTimeout which will call deleteIt on completion.
On completion of deleteIt, call typeIt again.
Sample Fiddle
You typeit will look something like this:
function typeIt() {
var t_interval = setInterval(function() {
if (chIndex <= strings[index].length)
span.innerHTML = strings[index].substring(0, chIndex++);
else {
type = false;
// This is to be executed once action is completed.
window.clearInterval(t_interval);
}
}, 20)
}

Javascript Add fadeIn to the loading Div

I have this code which loads an external local page into a div:
function load(url) {
document.getElementById("myDiv").innerHTML='<object type="text/html" data="'+url+'"></object>';
return false;
}
How can I make it fadeIn instead of just appearing? I would prefer if it was pure javascript
I found a nice fadeIn function in this answer and applied it to your load function.
Fiddle
function load(url) {
var myDiv = document.getElementById("myDiv");
myDiv.innerHTML='<object type="text/html" data="'+url+'"></object>';
fadeIn(myDiv);
return false;
}
function fadeIn(el) {
el.style.opacity = 0;
var tick = function() {
el.style.opacity = +el.style.opacity + 0.01;
if (+el.style.opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16)
}
};
tick();
}
load('foo');
The easiest way to do so is to add to your html jQuery:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
And then in your js file use .fadeIn() method on myDiv.
Remember to link jQuery before you link the .js file
Or if you can't use jQuery create animate classes in css:
#keyframes fadeIn {
to {
opacity: 1;
}
}
.fade-in {
opacity: 0;
animation: fadeIn .5s ease-in 1 forwards;
}
.is-paused {
animation-play-state: paused;
}
and then use this code in js:
var el = document.querySelector('.js-fade');
if (el.classList.contains('is-paused')){
el.classList.remove('is-paused');
}
The last thing you need to do is to add to myDiv classes of js-fade and fade-in is-paused.
The aforementioned code is qute general so adapt it to your needs

How to make a text flash in html/javascript?

I know flashing text is banned at many places but still as my client requires it, I need to flash one line of text using HTML, JavaScript which ever is feasible. I would like the text to appear and disappear within seconds and continue this cycle.
I know text-decoration:blink in CSS can do this but it only works in FireFox, Opera. And I need this to work in all browsers Firefox, Chrome, Safari, IE. I have searched and tried a lot of Javascript codes but none seem to be working.
So any one who knows how to do this, please post a working version of code which does flash the text in all browsers.
var blink_speed = 1000; // every 1000 == 1 second, adjust to suit
var t = setInterval(function () {
var ele = document.getElementById('myBlinkingDiv');
ele.style.visibility = (ele.style.visibility == 'hidden' ? '' : 'hidden');
}, blink_speed);
<div id="myBlinkingDiv">Hello World, blinking is back!</div>
I feel dirty.
You can do something like this:
<div id="Foo">Blink</div>
With the script:
$(document).ready(function() {
var f = document.getElementById('Foo');
setInterval(function() {
f.style.display = (f.style.display == 'none' ? '' : 'none');
}, 1000);
});
Sample: http://jsfiddle.net/7XRcJ/
If you're not using jQuery, you can try something like this:
window.addEventListener("load", function() {
var f = document.getElementById('Foo');
setInterval(function() {
f.style.display = (f.style.display == 'none' ? '' : 'none');
}, 1000);
}, false);
Various browsers have different ways of binding event handlers, so I would strongly suggest using some sort of cross-browser library for this sort of thing if possible.
You can also try using the onload event in the body tag. Here's a full example that I've tested in FF and IE7:
function blink() {
var f = document.getElementById('Foo');
setInterval(function() {
f.style.display = (f.style.display == 'none' ? '' : 'none');
}, 1000);
}
<html>
<body onload="blink();">
<div id="Foo">Blink</div>
</body>
</html>
if you use jQuery you can do something like
<div id="msg"> <strong>This will blink</strong> </div>
<script type="text/javascript" />
function blink(selector){
$(selector).fadeOut('slow', function(){
$(this).fadeIn('slow', function(){
blink(this);
});
});
}
$(function() {
blink('#msg');
});
</script>
Have a look at this snippet.
function blinkIt() {
var blinks = document.getElementsByClassName("blink");
for(var i = 0, l = blinks.length; i < l; i++){
var blink = blinks[i];
var visiblity = blink.style.visibility;
blink.style.visibility = visiblity == 'visible' ? 'hidden' : 'visible';
}
}
setInterval(blinkIt, 500 /* blinking interval in ms */);
This solution will make all elements with class blink blinking.
EDIT: Tested on Firefox, Chrome and IE9.
Using JavaScript and the Web Animation API!
elem.animate([{opacity:0},{opacity:1}],{duration:300,iterations:Infinity})
<h1 id="elem">WTF</h1>
Using CSS #keyframes!
#elem {
animation: blink 0.3s infinite
}
#keyframes blink {
from {
opacity: 0
}
to {
opacity: 1
}
}
<h1 id="elem">WTF</h1>
If you really have to do this then you can use the blink plugin for jQuery
http://www.antiyes.com/jquery-blink-plugin
$(document).ready(function() {
$('.blink').blink(); // default is 500ms blink interval.
//$('.blink').blink({delay:100}); // causes a 100ms blink interval.
});
You could make the text blink via jquery. Put the text you want to blink in a <blink> tag and the javascript below will make it blink. Increase the duration below if it blinks too fast.
<script type="text/javascript">
setInterval(function(){
$('blink').each(function(){
$(this).css('visibility' , $(this).css('visibility') === 'hidden' ? '' : 'hidden')
});
}, 250);
</script>
<blink>Text to blink here</blink>
You can use something like this
<html>
<head>
<style>
#blink{
color:black;opacity:1;font-size:3EM;
}
</style>
</head>
<body>
<div id="blink">
Poop
</div>
<script>
var ops,blink=document.getElementById('blink');
ops=1
setInterval(function (){
ops = (ops < 1) ? 1:0;
blink.style.opacity=ops;
},500);
</script>
</body>
function blink() {
var f = document.getElementById('Foo');
setInterval(function() {
f.style.display = (f.style.display == 'none' ? '' : 'none');
}, 1000);
}
<html>
<body onload="blink();">
<div id="Foo">Blink</div>
</body>
</html>
CSS:
.hidden { visibility: hidden; }
JS:
setInterval(blinkFunc, 200)
blinkFunc = function () {
var selector = '#some-selector';
jQuery(selector + ':visible').addClass('hidden');
jQuery(selector + ':not(:visible)').removeClass('hidden');
}
That's probably the most cross-browser. Note that Webkit does some crazy stuff with visibility so it might be easier to just change the color.

Categories