Vanilla JS Browser Default Java Script.
Wall Script
Follow Me:
Sunday, September 20, 2015

Vanilla JS Browser Default Java Script.

Recent days many are discussing about Vanilla JS a ZERO KB framework, it is basically plain/default JavaScript like vanilla ice cream (default flavor) and it is not really a library or a framework. Nowadays JavaScript DOM methods has been improved a lot, it is very powerful in speed operations per second. So that you no need to use any external libraries like Jquery etc.. If you are working for simple mobile or web application, I suggest use following plain JavaScript scripts.

Getting Started with Vanilla JS


Download Script     Live Demo 1     Live Demo 2

The term Vanilla is refers to raw or plain JavaScript.

Start Vanilla - The Document Ready Event
Code runs after the browser finishes loading the document, including images and banner ads.
document.addEventListener('DOMContentLoaded', function()
{
//JavaScript methods go here.
});

Click Event
Contains plain JavaScript code, here linkID is the ID name of anchor tag. You can prevent the default behavior by calling e.preventDefault();
document.addEventListener('DOMContentLoaded', function()
{
//Click Event Code 
document.querySelector("#linkID").addEventListener("click", function(e)
{
alert("Click event triggered");
e.preventDefault();
});

});

//HTML Code
<a href="#" id="linkID">Click Event</a>

Hide & Show Div
The divBlock slowly disappears when clicked hideLink.
document.querySelector("#hideLink").addEventListener("click", function()
{
document.getElementById('divBlock').style.display = 'none'
});

document.querySelector("#showLink").addEventListener("click", function()
{
document.getElementById('divBlock').style.display = ''
});

//HTML Code
<a href="#" id="hideLink">Hide</a> --- <a href="#" id="showLink">Show</a>
<div id="divBlock">

</div>

Add & Remove Class
Applying and Removing a HTML Class.

CSS Code
You have to include following CSS code within the tag HEAD of the document
.hidden{display:none}

You can use following code with in the function HTMLElement.classList, this allows to add or remove the class of an element.
document.getElementById('divBlock').classList.add('hidden');

document.getElementById('divBlock').classList.remove('hidden');

//HTML Code
<a href="#" id="hideLink">Hide</a> --- <a href="#" id="showLink">Show</a>
<div id="divBlock">

</div>

Toggle Class
This method simply toggles the visibility of elements, here the code is adding and removing the class hidden.
document.querySelector("#toggle").addEventListener("click", function()
{
document.getElementById('divBlock').classList.toggle('hidden');
});
//HTML Code
<a href="#" id="hideLink">Toggle</a>
<div id="divBlock">

</div>

Mouse Over & Mouse Out
Changing the div behavior based on mouse moments.

HTML Code
<div class="grid"></div>
<div class="grid"></div>
<div class="grid"></div>
<div class="grid"></div>

JavaScript
Here grid is the class name of div tags. Using this calling the selected DOM element.
//MouseOver
[].forEach.call(document.querySelectorAll(".grid"), function(el) {
el.addEventListener("mouseover", function() {
this.classList.add('hover');
});
});

//MouseOut
[].forEach.call(document.querySelectorAll(".grid"), function(el) {
el.addEventListener("mouseout", function() {
this.classList.remove('hover');
});
});

CSS Code
.grid
{
width:180px; height: 100px;
background-color:#333333;display: block;cursor:pointer;
float:left;margin-right: 10px
}
.hover
{
background-color: #cc0000 !important
}

Live POST Update and Delete Records with Vanilla JS
A simple demo project, you can instantly upload and delete news feed without refreshing the page.

HTML Code
Update box with news feed result. Live Demo
<textarea id="updateText"></textarea>
<input type="button" id="updateButton" value="POST" />

<div id="newsFeed">
//Record One
<div class="feed">
The Wall Script http://thewallscript.com
<a href="#" class="delete">X</a>
</div>
//Record Two
<div class="feed">
9lessons Blog http://9lessons.info
<a href="#" class="delete">X</a>
</div>
........
........
........
</div>

Ajax Post
Contains JavaScript code querySelector("#updateButton").addEventListener("click", function(){} - updateButton is the ID name of the button. Using document.getElementById("updateText").value; calling update textbox value. I did simplified a function called vanillaGetPost, you will find this in vanillaFunctions.js. Take a look at the Live Demo
//Update content.
var newsFeed=document.getElementById('newsFeed');
document.querySelector("#updateButton").addEventListener("click", function()
{
var p = document.createElement("div"),
newsFeed = document.getElementById("newsFeed"),
content = document.getElementById("updateText").value;
var html ;

var data='update='+content;
vanillaGetPost('POST', 'post.php', data, function(data)
{
var updateText= document.getElementById("updateText");
html='<a class="delete" href="#" onclick="deleteButton(this)" title="Delete">X</a>';
p.innerHTML = data+html; //User update with delete button HTML code. 
newsFeed.insertBefore(p, newsFeed.firstChild);
vanillaFadeEffect('fadeIn',newsFeed.firstChild, 1000);
updateText.value='';
updateText.focus();
});

});

post.php
You have to write database connection for inserting update.
<?php
if($_POST['update'])
{
echo htmlentities($_POST['update']);
// Write database connection here. 
}
?>

Delete Records
Using this.parentNode calling parent DIV DOM element and applying fadeOut effect.
//Delete click event
[].forEach.call(document.querySelectorAll(".delete"), function(el)
{
el.addEventListener("click", function() {
var parent = this.parentNode;
vanillaFadeEffect('fadeOut',parent, 1000); //vanillaFunctions.js
});
});

Final JavaScript Code
You can include all of the code here.
<script src="js/vanillaFunctions.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function()
{
//Textarea focus
window.onload = function() {
document.getElementById("updateText").focus();
};

var newsFeed=document.getElementById('newsFeed');

//Delete click event
.......
.......
.......

//Update content.
.......
.......
.......

});

function deleteButton(id)
{
var parent = id.parentNode;
//Delete Ajax
vanillaFadeEffect('fadeOut',parent, 1000);
}
</script>

Download the script, you will find out vinillaFunctions.js

vanillaGetPost Function
Ajax function for POST and GET methods.
function vanillaGetPost(type, url, data, success)
{
if(type=='GET')
{
url=url+'?'+data;
data='';
}
var r = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
r.open(type, url, true);
r.onreadystatechange = function () {
if (r.readyState > 3 && r.status === 200){
success(r.responseText);
}
};
r.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
r.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
r.send(data);
return r;
}

vanillaFadeEffect Function
FadeIn and FadeOut animation effect.
function vanillaFadeEffect(effect, element, speed)
{
var A=0;
if(effect === 'fadeOut')
A=1;

if ( ! element.style.opacity)
element.style.opacity = parseInt(A);

var start = null;
window.requestAnimationFrame(function animate(timestamp) {
start = start || timestamp;
var progress = timestamp - start;

if(effect === 'fadeOut')
element.style.opacity = 1 - progress / speed;
else
element.style.opacity = progress / speed;

if (progress >= speed) {
if(effect === 'fadeOut')
element.style.display = 'none';
else
element.style.display = '';

}
else
{
window.requestAnimationFrame(animate);
}
});

}
Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


12 comments:

  1. Thanks for sharing more info and sample codes! I've been playing around with this recently too. :)

    ReplyDelete
  2. Its kind of native javascript, what I got that, you don't have to use external libraries (ie, jQuery, Yui) for complex javascript operation.

    Its something like http://youmightnotneedjquery.com/ . I can remember Srinivas shared this in his fb wall few months ago.

    ReplyDelete
  3. how to post photo with text by vanilla js

    ReplyDelete
  4. thank you....

    by the way, nice post as always :)

    ReplyDelete
  5. I haven't tried the examples given here, but in past I have tried using javascript to get data continuously after some time interval but ended up with some issue. The issue was that other javascript functions were not able to run at the same time as this one was running. Later when I shifted to JQuery it all worked well.
    Any help here?? :-)

    ReplyDelete
    Replies
    1. Vanilla is just for light weight applications.

      Delete
  6. Hi Srinivas anna,

    I'm following your blog for 4 years now and i must say, Your articles are unique.

    ReplyDelete

Make in India