Category: JavaScript

How to embed HTML into a web page without using “iframe

While coding my personal website, I ran into a problem: I want to create a modal window with an “iframe” tag, but Google Translate does not support text in the iframe. So I tried to embed another HTML file in index.html with JavaScript or PHP.

GOAL

The goal today is to embed sub.html in index.html without using iframe tags so that Google Translate will work for the embedded text.

Below is how to embed the code in an iframe tag.

<iframe src="sub.html"></iframe>

Environment

PHP8.3.8
Latest Google Chrome (Version 127.0.6533.90)

Method

Method1: Using php include function

<?php include 'sub.html'; ?>
//<?php include('sub.html'); ?> also works

Change index.html into index.php to use PHP function in index file.
Or you can use html as PHP by using “AddType” in .htaccess. Reference: Parse HTML as PHP using HTACCESS File

Method2: JQuery .load() in JavaScript

<div id="frame-content"></div>

<!-- need to read jQuery -->
<script src="jquery.min.js"></script>

<script>
    $("#frame-content").load('sub.html');
</script>

Trouble Shooting

Opening index.html in a local environment causes a CROS policy error as below. For correct results, we must use a web server or a local HTTP server.

Access to XMLHttpRequest at 'file:///C:/.../sub.html' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.

Reference: How do you set up a local testing server?

Implementation Of Ajax (Search Suggestion)

GOAL

Today’s goal is to implement a search suggestion as below. The suggestion should be displayed without page transition while inputting the search word.

Environment

Windows10
XAMPP 7.4.10

What is Ajax

AJAX, Asynchronous JavaScript And XML, is a term that refers to a group of Web development techniques for asynchronous communication on the client side using JavaScript. Please check “What Is AJAX (and Asynchronous Communication)?” for details about ajax.

The following is a brief explanation about the ajax mechanism.

How Ajax works

In Ajax, the 2 system “sending the request and getting the response from the server” and “get the data from the browser and reflect the received data to the browser” are separated. So users can operate on the browser while waiting the response.

This image has an empty alt attribute; its file name is image-2.png
(more…)

How To Create JSON Data In PHP

JSON is used for data exchange in PHP. But how can I create json data in php and pass it to JavaScript?

GOAL

Today’s goal is to generate Json data from PHP array and get the data in JavaScript. This can be used when getting data from the server in PHP and processing the data in JavaScript.

Method

1. Create a nested array data

<?php
$teachers = []
$teachers = [
    "101" => [
        "name" => "Poppins",
        "class" => "music",
    ],
    "102" => [
        "name" => "Dolittle",
        "class" => "natural history",
    ],
    "103" => [
        "name" => "Snape",
        "class" => "pharmacy",
    ],
];
?>

You can create the nested array with for loop, too.

<?php
$teachers = [];
$data_set = [["101", "Poppins", "music"],["102", "Dolittle", "natural history"],["103", "Snape", "pharmacy"]];
for($i=0; $i < count($data_set); $i++){
    $teacher = $teachers_list[$i];
    $teachers += array($teacher[0] => array("name" => $teacher[1], "class" => $teacher[2]));
}
?>

2. Generate Json with json_encode() function

<?php
echo json_encode($teachers);
?>
//output => {"101":{"name":"Poppins","class":"music"},"102":{"name":"Dolittle","class":"natural history"},"103":{"name":"Snape","class":"pharmacy"}}

3. Get the data in JavaScript

Get the json string from the variable $teachers and convert the string to the Object with JSON.parse().

<script type="text/javascript">
    var json_str='<?php echo json_encode($teachers); ?>';
    var json_obj = JSON.parse(json_str);
    console.log(json_str)
    for(k in json_obj){ // get keys
        var teacher = json_obj[k];
        console.log("name: " + teacher['name']);
        console.log("class: " + teacher['class']);
    }
/*
--console output--
name: Poppins
class: music
name: Dolittle
class: natural history
name: Snape
class: pharmacy
*/
</script>

Source Code

The Completed Code is as below.

<?php
$teachers = [];
$teachers = [
    "101" => [
        "name" => "Poppins",
        "class" => "music",
    ],
    "102" => [
        "name" => "Dolittle",
        "class" => "natural history",
    ],
    "103" => [
        "name" => "Snape",
        "class" => "pharmacy",
    ],
];
?>

<script type="text/javascript">
    var json_str='<?php echo json_encode($teachers); ?>';
    var json_obj = JSON.parse(json_str);
    console.log(json_str)
    for(i in json_obj){
        var teacher = json_obj[i];
        console.log("name: " + teacher['name']);
        console.log("class: " + teacher['class']);
    }
</script>

How To Embed CodePen in Your Website.

I tried CodePen belatedly.

GOAL

To embed CodePen viewer in my WordPress web site as below.

What is CodePen?

CodePen is a web service to build, test, share and discover front-end code such as html, css and JavaScript.

CodePen is a social development environment for front-end designers and developers. 

from CodePen

Start Coding

In my case, I’ve signed up at first, but you can just start coding by clicking “Start Coding” button.

Embed CodePen

Click “Embed” button at the lower bottom of the page after coding.

Select the style of editor and change the size of the window. you can use anything you like. I chose “HTML (recommended)” and copy the code.

Paste the copied code in the Custom HTML block as below.

See the Pen watching by HanakoSonobe (@s-nako) on CodePen.

[JavaScript] Two Types Of Canvas Size.

GOAL

To understand canvas size, canvas.width and canvas.height, and how to set the size.

2 types of canvas size.

  • width and height set by css that determine the size of canvas element relative to the window size
  • canvas.width and canvas.height are reference values that determine the criteria for the image to display

These two sizes have separate meanings and are set independently.

What is the difference between canvas.width and canvas.height?

<style type="text/css">
    #canvas-container{
        width: 800px;
        height: 500px;
        border: solid 2px;
    }
</style>
<div id="canvas-area">
    <canvas id="canvas-container" width=800 height=500></canvas>
</div>

Change the canvas element size (display size).

<style type="text/css">
    #canvas-container{
        width: 400px;
        height: 400px;
        border: solid 2px;
    }
</style>
<div id="canvas-area">
    <canvas id="canvas-container" width=800 height=500></canvas>
</div>

Change the canvas buffer size.

<style type="text/css">
    #canvas-container{
        width: 800px;
        height: 500px;
        border: solid 2px;
    }
</style>
<div id="canvas-area">
    <canvas id="canvas-container" width=250 height=600></canvas>
</div>

[JavaScript] Drifting Effect

I created drifting animation for my friend’s website the other day.

GOAL

To create animation of drifting items.

Source Code

<style type="text/css">
    #canvas-area {
        width: 100%;
        height: 100%;
        position: relative;
    }
    #canvas-container{
        width: 1000px;
        height: 500px;
    }
</style>
<div id="canvas-area">
    <canvas id="canvas-container"></canvas>
</div>
<script type="text/javascript">
    //set canvas
    var canvasArea = document.querySelector('#canvas-area');
    var canvas = document.querySelector('#canvas-container');
    var ctx = canvas.getContext('2d');
    var canvas_width = canvas.width;
    var canvas_height = canvas.height;

    var last_time;

    //settings
    var item_num = 20;
    var img_src_array = ['img1.png', 'img2.png', 'img3.png', 'img4.png', 'img5.png'];
    var first_start_x = canvas_width - 100;
    var first_start_y = canvas_height - 100;

    //Item Object
    var Item = function(input_img){
        img_width = input_img.width;
        img_height = input_img.height;
        this.alpha = 1.0;
        this.img = input_img;
        this.start_x = first_start_x;
        this.start_y = first_start_y;
        this.x = this.start_x ;
        this.y = this.start_y;
        this.rotate = Math.random()*Math.PI*2;
        console.log(img.src)
        this.speed=[parseInt((Math.random())*10), parseInt(Math.random()+2)];
    };
    Item.prototype.update = function(){
        this.x -= this.speed[0];
        this.y -= this.speed[1];
        this.alpha *= 0.9;
        if(this.alpha < 0.1 ){
            this.alpha = 0;
        }
        
        if(this.x+this.img.width < 0 || this.x > canvas_width || this.y + this.img.height < 0){
            this.speed=[parseInt((Math.random())*10), parseInt(Math.random()+2)];
            console.log(`${this.start_x}:${this.start_y}`)
            this.x = this.start_x;
            this.y = this.start_y;
            this.rotate = Math.random()*Math.PI*2;
            this.alpha =1.0;
        }
    };
    Item.prototype.display = function(){
        ctx.globalAlpha = this.alpha;
        ctx.translate(this.x + img_width/2, this.y+ img_height/2);
        ctx.rotate(this.rotate);
        ctx.drawImage(this.img, -img_width/2, -img_height/2, img_width/2, img_height/2);
        ctx.rotate(-this.rotate);
        ctx.translate(-this.x - img_width/2, -this.y - img_height/2);
    };

    //create item array
    var items = [];
    var item_add = function(img){
        img.width = 100;
        img.height = 100;
        items.push(new Item(img));
        initialize();
    };

    for(var i=0; i<item_num; i++){
        img = new Image();
        img.src = img_src_array[parseInt(Math.random()*img_src_array.length)];
        img.onload = item_add(img);
    }

    function initialize(){
        if(items.length == item_num){
            last_time = new Date().getTime();
            animation();
        }
    }

    //animation
    function animation(){
        //callback
        window.requestAnimationFrame(animation);
        now_time =  new Date().getTime();
        //clear window
        if((now_time - last_time) > 100){
            last_time = now_time
            ctx.clearRect(0, 0, canvas_width, canvas_height);
            for(var i=0; i<item_num; i++){
                items[i].display();
                items[i].update();
            }
        }
    }
</script>

Item Object

Item Object has local variables.

alphaalpha channel value of this Item
imgHTMLImageElement of this Item
start_x, start_ythe position where this Item appears
x, ythe position where this Item exists
rotatethe rotation angle of this Item
speedthe moving speed of this Item
    //Item Object
    var Item = function(input_img){
        img_width = input_img.width;
        img_height = input_img.height;
        this.alpha = 1.0;
        this.img = input_img;
        this.start_x = first_start_x;
        this.start_y = first_start_y;
        this.x = this.start_x ;
        this.y = this.start_y;
        this.rotate = Math.random()*Math.PI*2;
        this.speed=[parseInt((Math.random())*10), parseInt(Math.random()+2)];
    };

Item Object has 2 functions.

update()update position and alpha channel
display()Rotation and movement by coordinate transformation
translate->rotate->draw->rotate(reverse)->translate(reverse)
    Item.prototype.update = function(){
        this.x -= this.speed[0];
        this.y -= this.speed[1];
        this.alpha *= 0.9;
        if(this.alpha < 0.1 ){
            this.alpha = 0;
        }
        
        if(this.x + this.img.width < 0 || this.x > canvas_width || this.y + this.img.height < 0){
            this.speed=[parseInt((Math.random())*10), parseInt(Math.random()+2)];
            console.log(`${this.start_x}:${this.start_y}`)
            this.x = this.start_x;
            this.y = this.start_y;
            this.rotate = Math.random()*Math.PI*2;
            this.alpha =1.0;
        }
    };
    Item.prototype.display = function(){
        ctx.globalAlpha = this.alpha;
        ctx.translate(this.x + img_width/2, this.y+ img_height/2);
        ctx.rotate(this.rotate);
        ctx.drawImage(this.img, -img_width/2, -img_height/2, img_width/2, img_height/2);
        ctx.rotate(-this.rotate);
        ctx.translate(-this.x - img_width/2, -this.y - img_height/2);
    };

Create Item instances

Each image is assigned to the Item object randomly.

for(var i=0; i<item_num; i++){
        img = new Image();
        img.src = img_src_array[parseInt(Math.random()*img_src_array.length)];
        img.onload = item_add(img);
    }

Animation function

Update() and display() each Items at regular intervals.

    //animation
    function animation(){
        //callback
        window.requestAnimationFrame(animation);
        now_time =  new Date().getTime();
        //clear window
        if((now_time - last_time) > 100){
            last_time = now_time
            ctx.clearRect(0, 0, canvas_width, canvas_height);
            for(var i=0; i<item_num; i++){
                items[i].display();
                items[i].update();
            }
        }
    }