JQuery on click for dynamically added elements – why it is not working?

Hi, in this writing i will be explaining you how to attach on click event for the dynamically created element to the html page.

Why i cant add on click event to the dynamically added element like static elements?

Because when you run javascript code in the page starts, jquery tries to find element you add event to it. But it cant find element because you will create element dynamically so you need to reconnect your element wity your function.

In this code below you make a click event listener to all of your page and when this event trigers it uses some kind of filter for the selector (id , class , element name) you passed as second paramater. And then it runs the function that you passed as third argument to this jquery event function.

In the end of the day you catch all click elements but runs just for your filtered element(s).

$(document).on('click','#element',function(){
    alert('Clicked')
 });

Full Example

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Element Visibility</title>
</head>

<body>
    
    <script>
        $(function () {
            // add element to the page dynamically
            $('body').append('<button id="element">Button</button>');

            // add on click listener for element
            $(document).on('click','#element',function(){
                alert('Clicked')
            });
        });
    </script>
</body>

</html>

How to detect when element is visible on screen with Javascript

When user comes to the page you may want to show them animation and if element is in the bottom of page, you need to wait untill element is visible on screen to run your animation. With this ready to use function you can add this functionality all elements on screen. Also i have a youtube video that explains how i wrote this function.

Ready to use full JS code

function gc_detect_visibility(query,custom_funtion){

    let calculator = function(query,custom_funtion){
        
        let element = document.querySelector(query);

        let element_top_offset = element.offsetTop;
        let element_bottom_offset = element.offsetHeight + element_top_offset;

        let screen_top_offset = window.scrollY;
        let screen_bottom_offset = screen_top_offset + window.innerHeight;

        if(element_top_offset > screen_top_offset && screen_bottom_offset > element_bottom_offset){
            custom_funtion(element);
        }
    } 

    calculator(query,custom_funtion);

    document.addEventListener('scroll',calculator.bind(null,query,custom_funtion));
}

Example usage

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Detect Visibility</title>
</head>

<body>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box" id="element"></div>
    <div class="box"></div>
    <div class="box"></div>
    <style>
        .box {
            width: 250px;
            height: 250px;
            background-color: blue;
            margin-bottom: 20px;
        }

        #element {
            background-color: red;
        }
    </style>
    <script>
        function gc_detect_visibility(query,custom_funtion){

            let calculator = function(query,custom_funtion){
                
                let element = document.querySelector(query);

                let element_top_offset = element.offsetTop;
                let element_bottom_offset = element.offsetHeight + element_top_offset;

                let screen_top_offset = window.scrollY;
                let screen_bottom_offset = screen_top_offset + window.innerHeight;

                if(element_top_offset > screen_top_offset && screen_bottom_offset > element_bottom_offset){
                    custom_funtion(element);
                }
            } 

            calculator(query,custom_funtion);

            document.addEventListener('scroll',calculator.bind(null,query,custom_funtion));
        }

        gc_detect_visibility('#element',function(element){
            console.log('element is visible');
        });

    </script>

</body>

</html>

Js detect element when visible on viewport

To do that as you can see in the video and the code i share with you above. We need to calculate if element is visible on screen by finding element top offset and screen top offset. If element top offset is higer than screen top offset and if element bottom offset is lower than screen bottom offset it makes element is visible on screen.

                let element_top_offset = element.offsetTop;
                let element_bottom_offset = element.offsetHeight + element_top_offset;

                let screen_top_offset = window.scrollY;
                let screen_bottom_offset = screen_top_offset + window.innerHeight;

                if(element_top_offset > screen_top_offset && screen_bottom_offset > element_bottom_offset){
                    custom_funtion(element);
                }

In the this part of the code we gave this functionality to the function.

Also we need to add this function into the scroll event also we need to add any element query selector into it. That is why we create another function for that in the fist lines of the function.

We created “calculator” function to add this functionality to scroll event. That makes our code run every scroll behavior. Also we bind our custom function to run when element is visible on screen or viewport.

With this approach you can add any functionality to your code. Change the calculation based on your situation and solve your problem with that.

PHP WordPress Delete All Posts with thumbnail image permanently

Delete all image, meta data and post permanently.


# delete all posts
$args = array(
    'post_type' => 'post',
    'posts_per_page' => -1,
    'post_status' => 'any'
);
$posts = get_posts($args);
foreach ($posts as $post) {
    # delete post thumbnail
    $thumbnail_id = get_post_thumbnail_id($post->ID);
    if ($thumbnail_id) wp_delete_attachment($thumbnail_id, true);
    wp_delete_post($post->ID, true);
}

Javascript check if element is visible on screen – check viewport

why we made in this code ? Line by line js code?

Check if element is visible in viewport using javascript library in javascript and add scroll event to detect when element is in screen:

Video and new version of this writing is here : https://gokhancelebi.net/how-to-detect-when-element-is-visible-on-screen-with-javascript/

Ready to Use FULL Code

// detect when element gets visible on scroll
    window.addEventListener("scroll", detect_visibility);

    // detect when screen opens for first time
    detect_visibility();

    function detect_visibility() {

        var element = document.getElementById("element");

        var top_of_element = element.offsetTop;
        var bottom_of_element = element.offsetTop + element.offsetHeight + element.style.marginTop;
        var bottom_of_screen = window.scrollY + window.innerHeight;
        var top_of_screen = window.scrollY;

        if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)) {
            // Element is visible write your codes here
            // You can add animation or other codes here
            alert("element is visible")
        } else {
            // the element is not visible, do something else
            alert("element is not visible")
        }

    }

detect_visibility ()

With this function i wrote you above you can detect if element inside secreen viewport. It calculates based on offset and element height. You can use this to implement lazyload or animations.

If you want to check if div is visible on screen use “getElemgetElementsByClassName()” or “getElementById” for div class or id

You can add animaton classes in the // Element is visible section of detect_visibility function

Element Top Offset

   var top_of_element = element.offsetTop;

In this line of code we get offset of element that we want to know if it is visibile.

Element Bottom Offset

var bottom_of_element = element.offsetTop + element.offsetHeight + element.style.marginTop;

In this line of code we get bottom offset of element

Window Bottom Offset and Top Offset

var bottom_of_screen = window.scrollY + window.innerHeight;
var top_of_screen = window.scrollY;

In the first line we get window screen’s bottom offset

In the second line we get windows screen’s top offset

Final : Calculate to detect if element is visible and shown on screen of user

if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)) {
      // Element is visible write your codes here
      // You can add animation or other codes here
      alert("element is visible")
} else {
      // the element is not visible, do something else
      alert("element is not visible")
 }

PHP IMAGE RESIZE FUNCTION FOR ALL FORMATS

You can use this function to resize and change quality of image for jpg, png, gif, bmp formats.

  • php image resize function for all image formats
  • parameters: image_path (required), new_width (optional), new_height (optional), quality (optional)
  • image_path: path to the image file
  • new_image_path: path to the resized image file
  • resize_x: resize by width
  • resize_y: resize by height
  • quality: JPEG quality (0-100)
  • returns boolean
# php image resize function for all image formats

function resize_image($image_path,$new_image_path,$resize_x,$resize_y,$quality) {
 
    // jpeg, png, gif or bmp?
    $ext = strtolower(pathinfo($image_path, PATHINFO_EXTENSION));
    
    // image create function
    switch ($ext) {
        case 'jpg':
        case 'jpeg':
            $image = imagecreatefromjpeg($image_path);
            break;
        case 'png':
            $image = imagecreatefrompng($image_path);
            break;
        case 'gif':
            $image = imagecreatefromgif($image_path);
            break;
        case 'bmp':
            $image = imagecreatefrombmp($image_path);
            break;
        default:
            return false;
    }
    
    // resize
    $resized = imagecreatetruecolor($resize_x, $resize_y);
    imagecopyresampled($resized, $image, 0, 0, 0, 0, $resize_x, $resize_y, imagesx($image), imagesy($image));
    
    // output
    switch ($ext) {
        case 'jpg':
        case 'jpeg':
            imagejpeg($resized, $new_image_path, $quality);
            break;
        case 'png':
            imagepng($resized, $new_image_path);
            break;
        case 'gif':
            imagegif($resized, $new_image_path);
            break;
        case 'bmp':
            imagewbmp($resized, $new_image_path);
            break;
    }
    
    // clear resources
    imagedestroy($image);
    imagedestroy($resized);
    
    return true;
}

How to resize an image in php

Woocommerce add to cart hook to dont allow user to add cart less than “_min_quantity” product meta

woocommerce add to cart hook to dont allow user to add cart less than "_min_quantity" product meta for wordpress

min quantity plugin example

If you want to dont allow user to add cart less than pack you can use this hook for it.

You can add this hook and function to functions.php of your theme or plugin.

This hook uses woocommerce_add_to_cart


add_action(
    'woocommerce_add_to_cart',
    'gc_add_to_cart_validation',
    10,
    6
);

function gc_add_to_cart_validation($product_id, $quantity, $variation_id = '', $variation = '', $cart_item_data = array())
{
    $product = wc_get_product($product_id);

    if ($product->is_type('variable')) {
        $variations = $product->get_available_variations();
        foreach ($variations as $variation) {
            if ($variation["attributes"]["attribute_pa_produkt-einheit"] == "kolli") {
                $min_quantity = get_post_meta($product_id, "_min_quantity", true);
                if ($quantity < $min_quantity) {
                    wc_add_notice(
                        sprintf(
                            __('You can not add less than %s kolli', 'woocommerce'),
                            $min_quantity
                        ),
                        'error'
                    );
                }
            }
        }
    } else {
        $min_quantity = get_post_meta($product_id, "_min_quantity", true);
        if ($quantity < $min_quantity) {
            wc_add_notice(
                sprintf(
                    __('You can not add less than %s kolli', 'woocommerce'),
                    $min_quantity
                ),
                'error'
            );
        }
    }
}

PHP CACHE EXAMPLE WITH TIMEOUT

<?php
// this is our base interface for cache class

interface CacheDriver
{
    public function get($key, $timeout = null, callable $callback = null);

    public function set($key, $value, $timeout = null);

    public function delete($key);

    public function deleteAll();

    public function deleteExpired();

    public function deleteExpiredByTimeout($timeout);

    public function deleteExpiredByKey($key);

    public function deleteExpiredByKeyTimeout($key, $timeout);
}


/**
 * Class Cache
 * static cache
 * save data in file
 * set file names as md5
 * use directory structure to save data
 * define timeout limit for cache files and if exceeded delete file
 * store cache as serialized time and data array
 *
 */
class FileCache implements CacheDriver
{

    /**
     * @var string
     */
    private static $cache_dir = 'cache/';

    /**
     * @var int
     */
    private static $cache_timeout = 3600;

    /**
     * @var string
     */
    private static $cache_ext = '.cache';

    /**
     * @param $key
     * @param int $timeout
     * @param callable $callback
     * @return bool
     * @description get data from cache by key
     */
    public function get($key, $timeout = null, callable $callback = null)
    {
        $file = self::$cache_dir . $key . self::$cache_ext;
        if (file_exists($file)) {
            $data = unserialize(file_get_contents($file));
            if (time() - $data['time'] < $timeout) {
                return $data['data'];
            }
        }

        if (is_callable($callback)) {
            $data = call_user_func($callback);
            $this->set($key, $data, $timeout);
            return $data;
        }

        unlink($file);

        return false;
    }

    /**
     * @param $key
     * @param $data
     * @return bool
     * @description set data and timeout to cache by key
     */

    public function set($key, $data, $timeout = null)
    {
        $file = self::$cache_dir . $key . self::$cache_ext;
        $data = array('time' => time(), 'data' => $data);
        file_put_contents($file, serialize($data));
        return true;
    }

    /**
     * @param $key
     * @return bool
     * @description delete cache by key
     */
    public function delete($key)
    {
        $file = self::$cache_dir . $key . self::$cache_ext;
        if (file_exists($file)) {
            unlink($file);
            return true;
        }
        return false;
    }

    /**
     * @return bool
     * @description delete all cache
     */
    public function deleteAll()
    {
        $files = glob(self::$cache_dir . '*' . self::$cache_ext);
        foreach ($files as $file) {
            unlink($file);
        }
        return true;

    }

    /**
     * @return bool
     * @description delete expired cache
     */
    public function deleteExpired()
    {
        $files = glob(self::$cache_dir . '*' . self::$cache_ext);
        foreach ($files as $file) {
            $data = unserialize(file_get_contents($file));
            if (time() - $data['time'] > self::$cache_timeout) {
                unlink($file);
            }
        }
        return true;

    }

    /**
     * @return bool
     * @description delete expired cache
     */
    public function deleteExpiredByTimeout($timeout)
    {
        $files = glob(self::$cache_dir . '*' . self::$cache_ext);
        foreach ($files as $file) {
            $data = unserialize(file_get_contents($file));
            if (time() - $data['time'] > $timeout) {
                unlink($file);
            }
        }
        return true;
    }

    /**
     * @return bool
     * @description delete expired cache
     */

    public function deleteExpiredByKey($key)
    {
        $file = self::$cache_dir . $key . self::$cache_ext;
        if (file_exists($file)) {
            $data = unserialize(file_get_contents($file));
            if (time() - $data['time'] > self::$cache_timeout) {
                unlink($file);
            }
        }
        return true;
    }

    /**
     * @return bool
     * @description delete expired cache
     */
    public function deleteExpiredByKeyTimeout($key, $timeout)
    {
        $file = self::$cache_dir . $key . self::$cache_ext;
        if (file_exists($file)) {
            $data = unserialize(file_get_contents($file));
            if (time() - $data['time'] > $timeout) {
                unlink($file);
            }
        }
        return true;
    }
}


class Cache extends FileCache
{
    public function __construct()
    {
        parent::__construct();
    }
}

$cache = new Cache();
$result = $cache->get("test", DEFAULT_CACHE_TIMEOUT, function () {
    return "data of cache";
});

PHP Woocommerce Delete Products With Variations and images

Delete products with all information

<?php


include __DIR__ . "/../../wp-load.php";

#delete woocommerce products from array with all images
$products = [1,2,3]; // product id's
foreach ($products as $product) {

    $product_sku = $product;
    $product_id = wc_get_product_id_by_sku($product_sku);

    if(!$product_id){
        echo "Product with SKU: " . $product_sku . " not found.<br>\n";
        continue;
    }

    #delete product variations by product id
    $variations = get_children(array(
        'post_parent' => $product_id,
        'post_type' => 'product_variation',
        'fields' => 'ids'
    ));

    foreach ($variations as $variation_id) {
        wp_delete_post($variation_id, true);
    }

    #delete product images
    $product_images = get_post_meta($product_id, '_product_image_gallery', true);
    if($product_images){
        $product_image_gallery = explode(',', $product_images);
        foreach ($product_image_gallery as $image_id) {
            wp_delete_attachment($image_id, true);
        }
    }

    #delete product
    if ($product_id) {
        wp_delete_post($product_id, true);
        echo "Product deleted: " . $product_sku . " " . $product_id . "<br>\n";
    }

}