Detect the End of CSS Animations and Transitions with JavaScript

Detect the End of CSS Animations and Transitions with JavaScript

In JavaScript, we can call the callback function once the animation is done. But in CSS, there is no option to perform any action after the end of the transition/animation. it's possible to detect the end of a CSS transition or ... Then bind the event with jQuery's one function, which ensures that it runs

Before CSS transition and animation (keyframes), to animate, we needed to code in JavaScript. But once these two properties were introduced, we can achieve complex animations with only CSS.

In JavaScript, we can call the callback function once the animation is done. But in CSS, there is no option to perform any action after the end of the transition/animation.

Whenever the transition is finished, the transitionend event will be triggered. We can use this event to find the end of the transition. We can also use it like ontransitionend.

If the browser is WebKit-based then we need to define the prefix for the event.

 "transition"      : "transitionend",
    "OTransition"     : "oTransitionEnd", // opera
    "MozTransition"   : "transitionend", // mozilla
    "WebkitTransition": "webkitTransitionEnd"

Let’s create a practical example to detect the end of a transition.

We are going to create a search box that will expand when we focus on the input.

HTML: Create an Input Box
<input type="text" class="search" placeholder = "Enter the text">
CSS: Add Style to the Input Box
.search {
  width : 200px;
  height :30px;
  border :5px solid red;
  border-radius : 10px;
  padding : 10px;
  color : blue;
  outline:none;
  transition : all .3s linear;
}

Once the input box is focused, we need to increase its width.

.expand {
  width : 50vw;
}
JavaScript: Add focus and focusout Listeners
let input = document.querySelector('.search');
input.addEventListener('focus',  function(ev, data) {
  input.classList.add('expand');
});
input.addEventListener('focusout',  function(ev, data) {
  input.classList.remove('expand');
});

This will create an expanding input box.

Now we need to detect the transition end event based on the browser. We can detect that by checking any of the transition events, available in the style attribute of any element.

function getTransitionEndEventName() {
  var transitions = {
      "transition"      : "transitionend",
      "OTransition"     : "oTransitionEnd",
      "MozTransition"   : "transitionend",
      "WebkitTransition": "webkitTransitionEnd"
   }
  let bodyStyle = document.body.style;
  for(let transition in transitions) {
      if(bodyStyle[transition] != undefined) {
          return transitions[transition];
      } 
  }
}

getTransitoin.js

// using above code we can get Transition end event name
let transitionEndEventName = getTransitionEndEventName();

Now, we need to add the event listener once the input is focused. For that, add the event listener inside the focus event callback:

input.addEventListener('focus',  function(ev) {
  input.classList.add('expand');
  input.addEventListener(transitionEndEventName, callback);
});

Once the transition is finished, the callback function will be called.

We also need to remove the transitionend event once the callback is executed, otherwise, the listener will keep running, causing it to run multiple times.

For example: On focusing input, the input box expands. This is one transition, and once the focus is out, the input box shrinks. This is also a transition. So, we need to remove the event listener inside the callback function.

function callback(ev) {
   
    console.log("transition  finished ");
    input.removeEventListener(transitionEndEventName, callback);
}

The complete code:

We can detect the name of the transition using the propertyName attribute in the ev argument of the callback function. We can also find the time taken to end the transition using the elapsedTime property.

Thanks for reading. I hope you liked this.

How to Create a Wikipedia Search API using JavaScript and CSS

How to Create a Wikipedia Search API using JavaScript and CSS

In this post, you will learn to create a **Wiki Search API based search engine**. Basically, there is a heading for telling about the search engine, a **search input**, and a button with an icon. The search input has also an **animation effect** on click, and the button for open random Wikipedia feeds. At first, it will show results about programming, you can change this in JS functions. When you will click on the **search button**, it will expand and becomes an input field. Then you can type any topic and press enter for getting the result.

How we can create a custom search engine for searching Wikipedia Infos? Solution: See this Custom Wikipedia Search Engine With JavaScript CSS, Wiki Search API Based.

Today you will learn to create a Wiki Search API based search engine. Basically, there is a heading for telling about the search engine, a search input, and a button with an icon. The search input has also an animation effect on click, and the button for open random Wikipedia feeds. At first, it will show results about programming, you can change this in JS functions. When you will click on the search button, it will expand and becomes an input field. Then you can type any topic and press enter for getting the result.

So, Today I am sharing Custom Wikipedia Search Engine With JavaScript and CSS. This program is based on the Wikipedia search API, which is provided by the wiki team for development purposes. There I have used many JS libraries like jQuery, bootstrap, solid.js, etc. This means it is not a pure JavaScript program. This program has AJAX-based search results without reloading.

If you are thinking now how this search program actually is, then see the preview given below.

Custom Wikipedia Search Engine With JavaScript CSS Source Code

Before sharing source code, let’s talk about it. First I have created a main div named container and placed a heading, a search input, and a button inside it. The layout is based on Bootstrap, as we know bootstrap creating responsive elements. In the HTML file, I have linked external files like CSS, JS, and other libraries’ CDN link.

Now using CSS I have placed all the elements in the right place, as you can see in the preview. With CSS I gave basic styles like size, position, margin, padding, color values, etc. There I have used CSS @Keyframe command for creating the search input animation, it is also handled by jQuery codes. I have used :after :before and transform command for creating the elements.

JS handling here the two main features of the program, one is search input toggle and the other is getting results using API over URL parameters. There is AJAX for getting data without load or reload. You can get results on typing like KeyUP function, you don’t have to press enter to get the result. I have created dynamic elements like div, heading, text in the JS file after getting results using jQuery .append command.

Left all other things you will understand after getting the codes, I can’t explain all in writing. For creating this program you have to create 3 files. First file for HTML, second File for CSS, and the third file for JavaScript. Follow the steps to creating this without any error.

index.html

Create an HTML file named ‘index.html‘ and put these codes given below.

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>Wikipedia Search Engine | Webdevtrick.com</title>
  <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/[email protected]/animate.min.css'>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.css'>
<link rel="stylesheet" href="style.css">
 
</head>
<body>
 
<div class="container">
      <div class="main">  
        <h1 class="text-center">Wikipedia Search Engine </h1>   
        <div class="content">                               
          <form>
            <input style="cursor: pointer;" type="text" id="search"/>
            <div class="after"></div>           
          </form>   
          <a class="icon-container" href="https://en.wikipedia.org/wiki/Special:Random" target="_blank" style="color: white">
            <i class="fas fa-random" id="randomIcon"></i>
          </a>                     
        </div>                            
      </div>
    </div>
 
<script src='https://code.jquery.com/jquery-3.3.1.js'></script>
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js'></script>
<script src='https://use.fontawesome.com/releases/v5.0.8/js/solid.js'></script>
<script src='https://use.fontawesome.com/releases/v5.0.8/js/fontawesome.js'></script>
<script  src="function.js"></script>
 
</body>
</html>

style.css

Now create a CSS file named ‘style.css‘ and put these codes given here.

/* Code By Webdevtrick ( https://webdevtrick.com ) */
@import url('https://fonts.googleapis.com/css?family=Bebas+Neue&display=swap');
@import url('https://fonts.googleapis.com/css?family=IBM+Plex+Serif');
 
html{
    min-height: 100vh;
 
}
 
body{
    background-color: white;   
}
 
.main{
    background-color: white;
}
 
h1 {
  font-family: 'Bebas Neue', cursive;
  color: #212121;
  margin-bottom: 15px;
  padding: 40px;
}
 
.content{
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-content: center;    
}
 
form {
    display: flex;
    flex-direction: row;    
}
 
.icon-container {
    margin-left: 10px;   
}
 
#randomIcon{
    margin-left: 10px;
    border-radius: 3px;
    cursor: pointer;
    vertical-align: text-bottom; 
    font-size: 40px;
    color: #ff444b;     
}
 
.wikiContent{    
    width: 35em;
    margin: 0 auto;
    border-radius: 3px;
    opacity: 0.7;
    margin-top: 10px;
    font-family: 'IBM Plex Serif', serif;
    padding: 3px 10px 0.1px 10px;
    max-width: 100%;
}
 
.wikiTitle{
    font-size: 18px;
    font-weight: bold;    
}
 
.wikiTitle > a{
    color: black
}
 
 
@keyframes alert {
    0%{
      transform: scale(0);
    }
    80% {
      transform: scale(1.2);
    }
    100% {
      transform: scale(1);
    }
  }
  form {
    transition: all 0.15s;
  }
  form.explode {
    transform: scale(1.4);
    opacity: 0;
  }  
  form {
    width: 36px;
    height: 36px;    
    display: block;
    box-sizing: border-box;
    position: relative;
  }
  input[type="submit"]{
    display: none !important;
  }
  input {
    width: 100%;
  }
  input {
    background: none;
    border: 3px solid #ff444b;
    border-radius: 26px;
    box-sizing: border-box;
    padding: 5px 15px 7px;
    font-size: 14px;
    color: #212121;
    z-index: 2;
    position: relative;
  }
  input:focus {
    outline: none;
  }
  .after {
    width: 36px;
    height: 36px;
    position: absolute;
    top: 1px;
    right: 0;
    z-index: 1;
  }
  form.open .after {
   cursor: pointer;
  }
  .after:before,
  .after:after {
    content: '';
    width: 13px;
    height: 3px;
    background-color: #ff444b;
    border-radius: 3px;
    position: absolute;
    transform-origin: 100% 100%;
  }
  .after:after{
    bottom: -3px;
    right: -3px;
    transform: rotate(45deg);
  }
  .after:before {
    top: -3px;
    right: -3px;
    transform: rotate(-45deg);
    opacity: 0;
  }
  form,
  form .after,
  form .after:before,
  form .after:after {
    animation-duration: 1.1s;
    animation-fill-mode: forwards;
  }
  form.in {
    animation-name: expand;
  }
  form.in .after:before {
    animation-name: beforemagic;
  }
  form.in .after:after {
    animation-name: aftermagic;
  }
  
  form.close,
  form.close .after,
  form.close .after:before,
  form.close .after:after {
    animation-direction: reverse;
  }
  form.close {
    animation-name: expand;
  }
  form.close .after:before {
    animation-name: beforemagic;
  }
  form.close .after:after {
    animation-name: aftermagic;
  }
  
  form.open {
    width: 250px;
    color: #000;
  }
  form.open .after {
    z-index: 3;
  }
  form.open .after:before {
    width: 20px;
    top: 9px;
    right: 13px;
    opacity: 1;
  }
  form.open .after:after {
    width: 20px;
    bottom: 10px;
    right: 15px;
  }
  
  @keyframes aftermagic {
    0%   {}
    10% {
      width: 24px;
      bottom: -10px;
      right: -10px;
    }
    15%{
      opacity: 1;
    }
    35% {
      width: 13px;
      bottom: -3px;
      right: -3px;
       opacity: 0;
      
    }
    25% {
      opacity: 0;
    }
    64% {
      opacity: 0;
    }
    65% {
      opacity: 1;
      width: 13px;
      bottom: -2px;
      right: -3px;
    }
    75% {
      width: 30px;
      bottom: 4px;
      right: 10px;
    }
    90% {
      width: 20px;
      bottom: 10px;
      right: 15px;
    }
    100% {
      width: 20px;
      bottom: 10px;
      right: 15px;
    }
  }
  @keyframes beforemagic {
    0%   {}
    50% {
      opacity: 0;
    }
    55% {
      opacity: 1;
      width: 13px;
      top: -4px;
      right: -3px;
    }
    65% {
      width: 30px;
      top: 6px;
      right: 10px;
    }
    80% {
      width: 20px;
      top: 9px;
      right: 13px;
    }
    100% {
      width: 20px;
      top: 9px;
      right: 13px;
      opacity: 1;
    }
  }
  @keyframes expand {
      0%   {
        color: transparent;
      }
    20% {
      width: 36px;
    }
    45% {
      width: 250px;
    }
    99% {
      color: transparent;
    }
      100% {
        width: 250px;
        color: #fff;
      }
  }

function.js

The final step, create a JavaScript file named ‘function.js‘ and put the codes.

$(document).ready(function () {
    const search = document.getElementById("search");
    var searchContent;   
 
    document.getElementById("search").addEventListener("input", () => {
        searchContent = search.value;             
 
        if (searchContent.length === 0){
            return;
        } else{
            ajax(searchContent);
        }        
    }, false); 
    
    ajax("programming");
    
    const s = $('input'),
        f  = $('form'),
        a = $('.after');       
 
    $("#search").keypress(e => {        
        if(e.which == 13) e.preventDefault();
    })
 
    s.focus(function(){
        if( f.hasClass('open') ) return;
        f.addClass('in');
        s.css("cursor", "text");
        setTimeout(function(){
            f.addClass('open');
            f.removeClass('in');        
        }, 1300);
    });
 
    a.on('click', function(e){
        e.preventDefault();
        if( !f.hasClass('open') ) return;
        s.val('');
        f.addClass('close');
        f.removeClass('open');
        s.css("cursor", "pointer")
        setTimeout(function(){
            f.removeClass('close');
        }, 1300);
    }) 
});
 
function ajax(search){
    $.ajax({
    type: "method",
    url: "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + search + "&prop=info|description&inprop=url|displaytitle&format=json&srlimit=10",
    data: "data",
    dataType: "jsonp",
    success: function (response) {
        showResults(response);       
    },
    error: function (){
        alert("Error retrieving search results, please refresh page.")
    } 
});
}
 
function showResults(response){   
 
    if (document.getElementsByClassName("wikiContent")){
        $(".wikiContent").remove();
    } 
 
    for(var i=0; i < 10; i++){       
        var result = response.query.search[i];
        var title = result.title;
        var description = result.snippet;
        var url = title.replace(/ /g, "_");
        var wikiURL = "https://en.wikipedia.org/wiki/" + url   
 
        $(".main").append(
            "<div class=\"wikiContent animated bounceInUp container\">" + 
            "<p class=\"wikiTitle\"><a href=\"" + wikiURL + "\"" +  "target=\"_blank\">"+ title +"</a></p>" +
            "<p class=\"wikiDescription\">" + description + "</p>" +          
            "</div>");          
       
    }
}

That’s It. Now you have successfully created Custom Wikipedia Search Engine With JavaScript CSS, Wiki Search API Based Program. If you have any doubt or questions comment down below.

Thanks For Visiting, Keep Visiting.

Teaching CSS to JavaScripters

Teaching CSS to JavaScripters

Teaching CSS to JavaScripters. Some JavaScript professionals do not know CSS as well as they’d like to. In order to help them, PPK decided to write a book “CDD for JavaScripters”, where he will explain CSS in terms that JavaScripters will understand. But what are those terms? What kind of teaching would JavaScripters expect? Is there a CSS mental model that is different from a JavaScript mental model? Is CSS a programming language? Does that matter for teaching or learning CSS?

But what are those terms? What kind of teaching would JavaScripters expect? Is there a CSS mental model that is different from a JavaScript mental model? Is CSS a programming language? Does that matter for teaching or learning CSS?

PPK will give a brief outline of where he’s standing right now on these questions. The majority of the session will be used for a discussion with the audience. How should he teach CSS? Why is it so hard for some to understand it? What are the least-understood parts of CSS? We hope this discussion will yield valuable feedback.

Traffic Lights Simulator with CSS and JavaScript

Traffic Lights Simulator with CSS and JavaScript

Traffic Lights Simulator with CSS and JavaScript. In this tutorial we're going to build a Traffic Light simulator using CSS and JavaScript.

In this tutorial we're going to build a Traffic Light simulator using CSS and JavaScript.