Javascrypt “Image.onload” fires even if the image is not found

I am trying to load some image for a HTML canvas game. And I want them to load before I start the game. So I created a function to load them synchronously before my game starts. But the problem is,

if the image does not exists, it still fires “Image.onload()”.

I want to return an object with “error=true” if the image doesn’t exist.
But couldn’t find a way.

Here is the function I wrote:

function loadImages(images) {
    return {
        list: images,
        loaded: {},
        failed: {},
        _load(src, name){
            return new Promise((resolve)=>{
                let image = new Image()
                image.onload = resolve({ name, src, image, error: false })
                image.onerror = resolve({ name, src, image: null, error: true })
                image.src = src
            })
        }
    }
}

let myLoader = loadImages("some image list")
let image = await myLoader._load("https://someUrl.com/img.png", "imageName")

console.log(image)

if you look at the console you’ll see the “onload” gets fired not “onerror”.

Digital business card generator [closed]

I just need to know how to generate a digital business card. I need to add that function to my project. I use PHP and JS. I only need to add a name, contact number, and email to that business card. actually, I have no idea how to do that. can someone help me to do that? it’s my university project. Thanks in advance.

Regards,
Samitha.

Why isn’t doc.data() a function in this if-statement?

When I remove the if-stament I get the data and doc.data() works, but I need to check for type ‘added’ so I don’t output existing data again and again.

With the if-statement, I get this error message:

Uncaught TypeError: doc.data is not a function

 async getChats(callback){
    const roomFilter = query(colRef, where("room", "==", this.room));
    const ordered = query(roomFilter, orderBy('created_at'));
    this.unsub = onSnapshot(ordered, (snapshot) => {
      let items = []
      snapshot.docChanges().forEach(doc => {
        if(doc.type === 'added'){
          items.push({ ...doc.data(), id: doc.id })
          console.log(items);
          callback(items);
      }})    
    });

Converting custom Leafet cluster from Vanilla Js code into React Js code

I’m trying to convert this code http://bl.ocks.org/gisminister/10001728 from Vanilla Js into React Js code. The code is about creating a custom UI for Leaflet clustering using a Pie Chart.

Here is the target.
enter image description here

Problem

I have copied and pasted the code from the blog but the cluster didn’t show as seen in the image below.
enter image description here

Code

Playground: https://codesandbox.io/s/learn-react-leaflet-cnk8tm?file=/src/components/CustomCluster/index.jsx

Steps to Reproduce

  1. Open and run the playground.
  2. Make sure you open the Custom Cluster page by adding /4 to the URL for example https://cnk8tm.csb.app/4 in the playground as seen in the image below.
    enter image description here

Question

I’m not familiar enough with Vanilla Js but I’m familiar enough with React Js.
So what’s wrong with my converted code (in the playground) and what’s the correct one?

Note

Actually, I have already created a custom Leaflet clustering in React Js using leaflet, react-leaflet, and react-leaflet-markercluster libraries here but still had a problem.

NS Error not initialized after capturing html canvas

I’m trying to record a svg animation using javascript/html. This is what i’ve tried so far:

<canvas id="canv">
    <svg width="370" height="370" viewBox="0 0 370 370" fill="none" xmlns="http://www.w3.org/2000/svg">
        <!-- my svg is here, full code is below because i don't think it's important -->
    </svg>
</canvas>
<style>
    @keyframes animation{
        from{
            opacity: 0;
            transform: translateY(20%);
        }to{
            opacity: 1;
            transform: translateY(0);
        }
    }
    #bubbles{
        animation: animation 1s linear;
    }
</style>
<script>
const canvas = document.getElementById("canv")

var videoStream = canvas.captureStream(30);
const render = () => {
    videoStream.getVideoTracks()[0].requestFrame();
}
setInterval(render, 33)
var mediaRecorder = new MediaRecorder(videoStream);
var chunks = [];
mediaRecorder.ondataavailable = function(e) {
    chunks.push(e.data);
};
mediaRecorder.onstop = function(e) {
    var blob = new Blob(chunks, { 'type' : 'video/mp4' });
    chunks = [];
    var videoURL = URL.createObjectURL(blob);
    video.src = videoURL;
};

mediaRecorder.start();
setTimeout(() => {
    mediaRecorder.stop();
}, 1000)
</script>

I have got the source code from https://medium.com/@amatewasu/how-to-record-a-canvas-element-d4d0826d3591 and i’m using firefox.
full source: https://paste.gg/p/anonymous/89d475bc50bc469dad827a620d3f7c02

Javascript async await timing

The following code is asynchronous.

async function test_function() {
    await (()=> {
        for(let i = 0; i < 10000000000; i+=1) {
        }
    })();
    console.log('hello 2');
}

test_function();
console.log('hello 1');

Output:

hello 1
hello 2

The function runs asynchronously and so we see hello 1 outputted before hello 2. However, both outputs are printed on the console at the same time rather than hello 2 being printed out a short while after hello 1. The program should execute code written directly after a call to an asynchronous function but that isn’t happening in this case. Why isn’t there a notable pause between the two logs?

What’s the use of callback form of setState given by useState hook?

Question is specifically related to functional components only

[state, setState] = useState(0);
// 1st way to increment by one
setState(state + 1);
// 2nd way to increment by one
setState((prevState) => prevState + 1);

What is the need for the second way? Is there any use case for that can only be met using the 2nd format? Is there any case where state !== prevState inside setState?

Placeholder in TextInput is not displaying any texts

My placeholder is not displaying the Placeholder text. Text input is displayed.
Placeholder text is also displayed while i am running on emulator. But when i install and run the code on my device. It doesnot display any placeholder text.

Here is my code

<View style={styles.root}>
<Text style={styles.title}>Create an account</Text>
            <CustomInput
                placeholder="Username"
                value={userName}
                setValue={setUserName}
            />
</View>

Stylesheet looks like this:

const styles = StyleSheet.create({
    root: {
        alignItems: 'center',
        padding: 20
    },
    title:{
        fontSize: 24,
        fontWeight: 'bold',
        color: '#051c60',
        margin:10
    }
})

;

Custom Input section looks like this:

<View style={styles.container}>
        <TextInput
            placeholder={placeholder}
            value={value}
            onChangeText={setValue}
            style={styles.input}
            secureTextEntry={secureTextEntry}
        />
    </View>

CSS for custom Input

const styles = StyleSheet.create({
    container:{
        backgroundColor:'white',
        width: '100%',
        borderColor:'#e8e8e8',
        borderWidth:1,
        borderRadius:5,
        paddingHorizontal:10,
        marginVertical:5,
    },
    input:{
        fontSize:16,
        color:'#000',
        paddingVertical:10,
    }
})

Creating comments and adding it into a comment box

Absolute beginner programmer here. I’m trying to create a comments box where whatever you type in the comments, will be stored in another div. I got some of it to work, it was able to append however, it disappears straight after. I want it to store the comments in the #comment-box div and when you enter another comment it stores it underneath. Here is my code so far

<div class="container">
    <h2>Leave us a comment</h2>
    <form>
       <textarea id="" placeholder="Add Your Comment" value=" "></textarea>
       <div class="btn">
           <input id="submit" type="submit" value="Comment">
           <button id="clear">  
            &#128591;</button>
       </div> 
    </form>
</div>
<div class="comments">
    <h2>Comments</h2>
    <div id="comment-box" value="submit">
    </div>
</div>

and my JS is

const field = document.querySelector('textarea');
const backUp = field.getAttribute('placeholder')
const btn = document.querySelector('.btn');
const clear = document.getElementById('clear')
const submit = document.querySelector('#submit')
// const comments = document.querySelector('#comment-box')
const comments = document.getElementById('comment-box')

field.onfocus = function(){
    this.setAttribute('placeholder','')
    this.style.borderColor = '#333'
    btn.style.display = 'block'
} // when clicking on this, placeholder changes into ' '.

field.onblur = function(){
    this.setAttribute('placeholder',backUp)
} //click away, placeholder returns

clear.onclick = function(){
    btn.style.display = 'none';
    field.value = ' '

submit.onclick = function(){
    submit.style.display = 'none';
    const content = document.createTextNode(field.value)
    comments.appendChild(content)

Where am I going wrong guys? Any feedback would be appreciated. Thank You

Test Stack in JavaScript – Pop and Peek and Swap returning error

I am trying to practice a stack test in javascript. I am returning what the test is asking for: 46 in the array of storage in the var stackHolder. However, the test result is not showing pop() and peek() functions correctly.

As you can see my consoles match the answer they are expecting, I want to check if I am incorrect or if there is a possible error on the validation to check the answers on their end.

Regarding the swap() – I am asking for a solution that works to get the result they are looking for, which is to swap 1,'{id: 1,value: "obj"}

Here is the code

export function stack( stackOperation, stackValue ) {
var stackHolder = {
count: 4,
storage : [
  1,
  '{id: 1,value: "obj"}',
  "stringHolder",
  46
]
};

var push = function(value) {
stackHolder.storage[stackHolder.count] = value;
return stackHolder.storage;
}

var pop = function() {
if (stackHolder.count === 0) {
  return [];
}

var poppedItem = stackHolder.storage[stackHolder.count];
delete stackHolder.storage[stackHolder.count];
stackHolder.count;

return poppedItem;
}

var peek = function() {
return [stackHolder.storage[0]];
}

var swap = function() {
return stackHolder.storage[1,0];
} 

switch(stackOperation) {
case 'push' : push(stackValue);
return stackHolder.storage;
break;
case 'pop': pop();  
return stackHolder.storage[3];
break;
case 'swap': swap();
return stackHolder.storage;
break;
case 'peek': peek();
return stackHolder.storage[3];
break; 
default:
console.log("DefaultResult", stackHolder.storage);
console.log("POP", stackHolder.storage[3]);
console.log("PEEK", stackHolder.storage[3]);
  return stackHolder.storage;
  }
}

-screen shot of computer validation for answers
enter image description here

–screen shot of console logs
enter image description here

-screen shot of Swap function error
enter image description here

Divide the html page into several pages automatically like MS WORD

Is ther any way to divide a html context contained div, p and table tages into separated pages in separated div tages (or at least just separated) for a defined height? (like ms word but online)

I want to create an html template for formal letters that might have multiple pages.
Expected a solution by using php or javascript or just html and css.

I use a persian font not english !

By the way, is there any other ways for creating those types of templates? (not using third party websites)… If yes, please give an example.

Note that I want to create pdf and image and ms word doc from that html too!

Thanks 🙂

Using Bootstrap inside a WordPress [header/footer.php ok] but got: ReferenceError: bootstrap is not defined @ functions.php

I have the following at header.php

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

And the following at footer.php

<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>

At functions.php, i have added a bootstrap modal inside wpb_hook_javascript (id=”tiopatinhas”)

All I want at this point is to show the modal programatically.

Also inside wpb_hook_javascript, I have the following

<script>
   var merda = document.getElementById("tiopatinhas");

The above one works fine, but then I try the following:

merda.show();   //Doesn't work

var merda = new bootstrap.Modal(document.getElementById('tiopatinhas')); //Doesn't work

$("#tiopatinhas").modal('show');  // Doesn't work

I know there’s something related to “childs”.
I know the last one is related to something called jQuery, which I read is deprecated. So, I don’t want to use it.

Any ideas how can I call the modal programatically?

PS I have a somehow good logic. In the past, I was an experienced C, C++ and ASM… in the 80s and 90s! :).
But, nowadays I know close to nothing about all of those frameworks, layers and so on.

Any help will be deeply appreciated.

How to access id of the modal globally using JavaScript Laravel Laravel

I’m have an html table with modal column (see image below for your reference)
Order Modal

Upon click the Order modal, I can access the its ID using onclick event in JavaScript
(var customer_id = $(this).val();)

I wanted to access and used it in my Add function using ajax but I’m having an error of “customer_id is not defined” when I tried to use it. Is there a way to fix it or do it properly.

This is my script

<script>
        $(document).ready(function () {
            // START OPEN CART MODAL FUNCTION
                $(document).on('click', '.viewCart', function (e) {
                    e.preventDefault();
                    var customer_id = 0;
                    var customer_id = $(this).val();
                    console.log(customer_id);

                    $.ajax({
                        type: "GET",
                        url: "/get-cart/"+customer_id,
                        dataType: "json",
                        success: function (response) {

                            if (response.data != null) {
                                console.log(response);
                                $('.OrderTbody').html("");
                                $.each(response.data, function (key, item) {
                                    $('.OrderTbody').append('<tr>
                                        <td>' + item.p_name + '</td>
                                        <td>' + item.c_qty + '</td>
                                        <td class="total">' + item.p_amt + '</td>
                                    <td><button type="button" value="' + item.c_id + '" class="btn btn-danger deleteListBtn btn-sm">Delete</button></td>
                                    </tr>');

                                });


                            }
                        }
                    });
                });
            // END OPEN CART MODAL FUNCTION

            // START ADD DATA FUNCTION
                    $(document).on('click', '.addToCart', function (e) {
                        e.preventDefault();
                        var data = {
                            'store': $('.sel_store').val(),
                            'product': $('.sel_product').val(),
                            'quantity': $('.sel_qty').val(),
                            // HOW TO INPUT Customer ID here, I tried this but im having an error of
                            // customer_id is not defined
                            'customer_id': customer_id,

                        }
                        $.ajaxSetup({
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                            }
                        });
                        $.ajax({
                            type: "POST",
                            url: "/cart-list",
                            data: data,
                            dataType: "json",
                            success: function (response) {

                            }
                        });

                    });
            // END ADD DATA FUNCTION

        });
        </script>