Wednesday, January 25, 2017

How to execute JavaScipt code inserted as innerHTML/text in DOM

If you tried to load scripts into a page using innerHTML on HTML element like div it will not be executed.

The alert statement in below code will not be executed since it is set as inner HTML.

document.getElementById('divTemp').innerHTML = "<scr" + "ipt>alert('hi')</scr" + "ipt>";

You can use eval() but there is an easier and better way to do this. That is to load the script element into DOM.

Here is an example -

        var script1 = document.createElement("script");
        script1.innerHTML = "alert('hi');";

In this way you can execute javascript statements set as innerHTML or text. This will help you to execute scripts that are loaded asynchronously using APIs.

Live example in codepen- 

Friday, January 13, 2017

How to scale html elements and fonts based on the container

When we generate html we can use '%' to scale the containers based on parent element. But html elements set with pixel value will not scale correctly if parent container size is changed.

Here is an example to scale html elements correctly. Keep in mind that this is not a solution for setting layouts for different devices like desktop, mobile and tablet. The example below can be used when you want the layout to look exactly the same and scale the content size and position based on parent element's size.

We can achieve this by setting the transform property
 transform: scale(scaleWidthValue,scaleHeightValue);

To scale twice the size -
-ms-transform: scale(2,2); /* IE 9 */
transform: scale(2,2); /* Safari */
transform: scale(2,2); /* Standard syntax */

Here is the codepen link to live example -

/********************* Here is the auto scaling html logic ***************/
transform-origin:top left;
.transform{/*not used directly here*/
    transform: scale(1.5,1.5); /* Standard syntax */
<div id="containerElement" >
<div id="contentElement" class="outerWrapperStyle transform">
<div class="contentStyle">
Outer wrapper  content.
<div class="innerWrapperStyle">
<div class="contentStyle">
Inner Wrapper Content
var containerElement = document.getElementById("containerElement");/*get container element*/
var contentElement = document.getElementById("contentElement");/*get content element*/

var scaleWidth = containerElement.clientWidth/contentElement.clientWidth; /*find out how much to scale for width*/
var scaleHeight = containerElement.clientHeight/contentElement.clientHeight; /*find out how much to scale for height*/  = "scale("+scaleWidth+","+scaleHeight+")"; /*set the scale on content Element*/