Does p5.js support steering wheel and gas pedal input?

I am writing a web based race car game using JavaScript and p5.js on a Mac.

Using the keyboard is not the best way to control the car 🙂 LoL!

Does p5.js or Javascript accept steering wheel input?
How would you go about reading input from a steering wheel,
and maybe gas pedals too via JavaScript?

Thanks!

why is there no quality selector for plyr in my code?

I am currently trying to use Plyr as a video player but i am running into an issue, i have multiple qualities but for some reason i am not able to switch as it doesnt even show me quality selector in the menu.

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{title}}</title>
    <link rel="stylesheet" href="https://cdn.plyr.io/3.7.8/plyr.css" />
    <style>
        body {
            margin: 0;
            overflow: hidden;
            background-color: black;
        }

        #playerContainer {
            width: 100vw;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
        }

        #myPlayer {
            max-width: 100%;
            max-height: 100%;
        }


        #backButton {
            position: absolute;
            top: 20px;
            left: 20px;
            display: flex;
            align-items: center;
            cursor: pointer;
        }

        #backButton img {
            width: 30px;
            height: 30px;
        }
    </style>
</head>

<body>
    <div id="playerContainer">
        <video id="myPlayer" controls >
            <!-- Video sources and captions will be dynamically added here -->
        </video>
    </div>
    <a id="backButton" href="/wait">
        <img src="{{ url_for('static', filename='arrowback.png') }}" alt="Back">
    </a>
    <script src="https://cdn.plyr.io/3.7.8/plyr.js"></script>
    <script>
        const timestampMovie = parseFloat('{{ timestamp }}');
        let title = '';

        document.addEventListener('DOMContentLoaded', () => {
            const response = {{api_response|safe}};

            if (response.title != '' && response.title != undefined) {
                title = response.title;
            }

            if (
                response != undefined &&
                response.Qualities != undefined &&
                response.Qualities != null
            ) {
                const myPlayer = new Plyr('#myPlayer', {
                    title: title,
                    settings: ['captions', 'quality', 'speed', 'loop'],
                    
                    
                });

                makePlayer(myPlayer, response.Qualities, response.Srtfiles);

            }
        });

        function extractNumericSize(label) {
    if (!label) {
        console.log('no label');
        return label; 
    }

    const matches = label.match(/d+/); 

    if (matches) {
        const numericSize = parseInt(matches[0], 10);

        const result = label.toLowerCase().includes('4k') ? 2160 : numericSize;

        console.log(`Label: ${label}, Numeric Size: ${numericSize}, Result: ${result}`);

        return result;
    }

    return label;
}






        function makePlayer(myPlayer, qualities, subtitles) {

            


            qualities.forEach((value, index) => {
                const track = document.createElement('source');
                const numericSize = extractNumericSize(value.quality);
                track.src = value.path;
                track.type="video/mp4"
                track.label=value.quality
                track.setAttribute('size', numericSize);
                myPlayer.media.appendChild(track);
            });


            subtitles.forEach((item, index) => {
                const track = document.createElement('track');
                track.kind = 'subtitles';
                track.label = item.caption;
                track.srclang = 'en'; 
                track.src = item.url;
                myPlayer.media.appendChild(track);
            });
        }


        document.addEventListener('DOMContentLoaded', () => {
            const backButton = document.getElementById('backButton');

            backButton.addEventListener('click', () => {
                const linkUrl = backButton.getAttribute('href');
                if (linkUrl) {
                    window.location.href = linkUrl;
                }
            });
        });


        const myPlayer = document.querySelector('#myPlayer');

        

        function sendTimestampUpdate(currentTimestamp) {
            const movieId = '{{ tmdb_id }}';
            const url = `/updatetime?id={{ user_id }}&mid=${movieId}&time=${currentTimestamp}&type=movie`;

            fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                })
                .then(response => {
                    if (response.status === 200) {
                        console.log('Timestamp updated successfully');
                    } else {
                        console.error('Failed to update timestamp');
                    }
                })
                .catch(error => {
                    console.error('Error updating timestamp:', error);
                });
        }
    </script>
</body>

</html>

This is an example api_response :

{
    "title": "The Dark Knight",
    "Qualities": [
        {
            "path": "https://usa7.shegu.net/vip/p1/movie_mp4_h264/2008/4/6/4056/movie.4056.2008.360p.H264.20210201053642.mp4?KEY1=4gkezDFUitoN_kyLdEVgDw&KEY2=1709461546&KEY3=298116&KEY4=world&KEY7=23&KEY8=298116",
            "quality": "360P"
        },
        {
            "path": "https://usa7.shegu.net/vip/p1/movie_mp4_h264/2008/4/6/4056/movie.4056.2008.360p.H264.20190414191652.mp4?KEY1=EsIAiKAdqXz8OmsvJ81i9A&KEY2=1709461547&KEY3=298116&KEY4=world&KEY7=23&KEY8=298116",
            "quality": "360P"
        },
        {
            "path": "https://usa7.shegu.net/vip/p1/movie_mp4_h264/2008/4/6/4056/movie.4056.2008.720p.H264.20210201053642.mp4?KEY1=mnAp7Fx036WKv0RAmHNehw&KEY2=1709461546&KEY3=298116&KEY4=world&KEY7=23&KEY8=298116",
            "quality": "720P"
        },
        {
            "path": "https://usa7.shegu.net/vip/p1/movie_mp4_h264/2008/4/6/4056/movie.4056.2008.1080p.H264.20190414191652.mp4?KEY1=DcmI-5u4RH4sSHoNrDBQhg&KEY2=1709461547&KEY3=298116&KEY4=world&KEY7=23&KEY8=298116",
            "quality": "720P"
        },
        {
            "path": "https://usa7.shegu.net/vip/p1/movie_mp4_h264/2008/4/6/4056/movie.4056.2008.1080p.H264.20210201053642.mp4?KEY1=X3fye4M72jQyivvlcLrS1g&KEY2=1709461546&KEY3=298116&KEY4=world&KEY7=23&KEY8=298116",
            "quality": "1080P"
        },
        {
            "path": "https://usa7.shegu.net/vip/p1/movie_mp4_h264/2008/4/6/4056/movie.4056.2008.4K.H264.20210201053642.mp4?KEY1=uNZKdm2bPlQgEELs0pAlLQ&KEY2=1709461546&KEY3=298116&KEY4=world&KEY7=23&KEY8=298116",
            "quality": "4K"
        }
    ],
    "Srtfiles": [
        {
            "caption": "English",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/751552/inf-tdk.EnglishHI.srt"
        },
        {
            "caption": "Chinese",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/306135/Batman.The.Dark.Knight.2008.1080p.BluRay.x264.YIFY.cht.srt"
        },
        {
            "caption": "German",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/986171/Subtitle.srt"
        },
        {
            "caption": "French",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/306055/Batman.The.Dark.Knight.2008.1080p.BluRay.x264.YIFY-FR.srt"
        },
        {
            "caption": "Russian",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/1146627/The.Dark.Knight.2008.Blu-Ray.RUS.SDH.full.voronine-1705263902.srt"
        },
        {
            "caption": "Spanish",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/306128/Batman.The.Dark.Knight.2008.1080p.BluRay.x264.YIFY-spa.srt"
        },
        {
            "caption": "Arabic",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/780237/The.Dark.Knight.2008.UHD.BluRay.2160p.DTS-HD.MA.5.1.HEVC.REMUX-FraMeSToR.srt"
        },
        {
            "caption": "Albanian",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/306082/Batman - The Dark Knight shqip.srt"
        },
        {
            "caption": "Brazilian",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/804386/Batman - The Dark Knight - 2008 DVDRip-XviD OpeD.srt"
        },
        {
            "caption": "Bulgarian",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/752848/inf-tdk.Bulgarian.srt"
        },
        {
            "caption": "Chinese (Simplified)",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/509258/Batman.The.Dark.Knight.chs.srt"
        },
        {
            "caption": "Chinese (Traditional)",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/509261/Batman The Dark Knight.srt"
        },
        {
            "caption": "Croatian",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/840962/inf-tdk.Croatian.srt"
        },
        {
            "caption": "Czech",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/306153/Batman.The.Dark.Knight.PROPER.DVDSCR.XViD-mVs-CD1.srt"
        },
        {
            "caption": "Danish",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/306212/Batman.The.Dark.Knight.PROPER.DVDSCR.XviD-contempt.srt"
        },
        {
            "caption": "Dutch",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/841230/The Dark Knight 2008 READNFO DVDSCREENER DVDR-The Batman.srt"
        },
        {
            "caption": "Finnish",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/936767/Batman.The.Dark.Knight.PROPER.DVDSCR.XviD-contempt.srt"
        },
        {
            "caption": "Greek",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/756295/TheDarkKnight_2008_DVD-DoNE.CD1.EL.srt"
        },
        {
            "caption": "Hebrew",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/973658/The.Dark.Knight.2008.BluRay.720p.DTS.x264.dxva-EuReKA.srt"
        },
        {
            "caption": "Indonesian",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/782646/The.Dark.Knight.2008.720p.BluRay.DTS.x264-ESiR.mkv.srt"
        },
        {
            "caption": "Italian",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/834815/dark_knight_ita_24fps.srt"
        },
        {
            "caption": "Japanese",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/925207/The.Dark.Knight.720p.BluRay.x264-iNFAMOUS.tikal.JPN.srt"
        },
        {
            "caption": "Korean",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/306101/Batman.The.Dark.Knight.2008.1080p.BluRay.x264.YIFY.smi"
        },
        {
            "caption": "Malay",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/806391/The.Dark.Knight.2008.1080p.BluRay.YIFY.Malay.Jkerr.Jk.srt"
        },
        {
            "caption": "Persian",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/811394/Assassin-s-Creed-2016.ALL.HDCAM.srt"
        },
        {
            "caption": "Polish",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/1100221/The.Dark.Knight.Polish-WWW.MY-SUBS.CO.srt"
        },
        {
            "caption": "Portuguese",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/947290/BATMAN-The dark.srt"
        },
        {
            "caption": "Portuguese (BR)",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/807022/Batman.The.Dark.Knight.PROPER.DVDSCR.XViD-mVs.srt"
        },
        {
            "caption": "Romanian",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/306191/Batman.The.Dark.Knight.2008.1080p.BluRay.x264.YIFY.srt"
        },
        {
            "caption": "Serbian",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/812660/DKTS.srt"
        },
        {
            "caption": "Slovak",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/306069/Batman - The Dark Knight 2008.srt"
        },
        {
            "caption": "Slovenian",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/1118510/inf-tdk.Slovenian.srt"
        },
        {
            "caption": "Swedish",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/306094/Batman.The.Dark.Knight.2008.1080p.BluRay.x264.YIFY.srt"
        },
        {
            "caption": "Thai",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/1128604/The.Dark.Knight.2008.720p.BluRay.x264-SiNNERS-1700043142.srt"
        },
        {
            "caption": "Turkish",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/808829/inf-tdk.Turkish.srt"
        },
        {
            "caption": "Ukrainian",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/1036579/The.Dark.Knight.2008.iT.WEB.uk-UA.srt"
        },
        {
            "caption": "Vietnamese",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/843521/The.Dark.Knight.2008.720p.BDRip.XviD.AC3-ViSiON_Vietnamese.srt"
        },
        {
            "caption": "Xx",
            "url": "https://images.shegu.net/movie_box/movie/srt/4/6/4056/305999/Batman.The.Dark.Knight.2008.1080p.BluRay.x264.YIFY.srt"
        }
    ]
}

The reason I’m using plyr.io is because it seems to bypass CORS and it is needed for my sources. I am aware that plyr doesn’t accept srt files and will fix that later, just need to get the quality selector working.

Image in xAxis Echarts

Change the style of image rendered in xAxisLabel of ECharts

does anyone know how can i style images in xaxis label in ECharts.
I used this example to render image in xAxisLabel richStyleExample
But somehow i cannot style the image (i only want to change the radius of it), however in the documentation I found this :

enter image description here

Does anyone knows how can I assign HTMLImageElement to this or somehow change the radius or style of the image?

I tried borderRadius in rich style, but it only works if the backgroundColor is not assign an image source.

Undefined timestamp Issue in frontend with javascript

I have created django consumers.py and a frontend in html and css to disply messages sent by a user, the profile picture of the sender and the username of the sender but anytime i open the browser, the message displays well and the username appears well but the time since always appear as undefined even though i printed the time stamp from the websocket and it shows the actual timp. ususally when i send a message, i see the received timestamp on the developer console but immediately i refresh the page it changes to undefine, i simply want to be able to display the time elapsed since a essage was sent, example X seconds ago, X minutes ago, X hours ago
my timestamp field is using timezone.now, Please i want a user to see the timesince a message was sent, the tmplate filere timesince isnt working though

this is my consumers.py


import os
import json
from channels.generic.websocket import AsyncWebsocketConsumer
from django.contrib.auth import get_user_model
from django.conf import settings
from channels.db import database_sync_to_async
from virtualrooms.models import VirtualRoom
from .models import Interaction
from django.templatetags.static import static
from datetime import datetime


User = get_user_model()

class DiscussionRoomConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = f"discussion_room_{self.room_name}"

        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

        # Get or create the VirtualRoom instance based on the provided room_name
        virtual_room = await self.get_virtual_room()

        if virtual_room is not None:
            # Send existing messages and old messages to the new user
            old_messages = await self.get_old_messages(virtual_room)
            for message in old_messages:
                await self.send(text_data=json.dumps({
                    'message': message['content'],
                    'username': await self.get_username(message['user']),
                    'user_picture': await self.get_user_profile_picture(message['user']),
                }))

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        user_id = self.scope["user"].id

        # Get the VirtualRoom instance based on the extracted room name asynchronously
        virtual_room = await self.get_virtual_room()

        # Check if the VirtualRoom instance exists
        if virtual_room:
            # Save message to the database with the VirtualRoom instance asynchronously
            await self.save_interaction_to_database(user_id, virtual_room, message)

            # Send message to the room group
            time_stamp = datetime.now().isoformat()
            username = await self.get_username(user_id)
            user_picture = await self.get_user_profile_picture(user_id)


            # Log the entire message data
            print("Sending message data:", {
                'message': message,
                'username': username,
                'user_picture': user_picture,
                'time_stamp': time_stamp,
            })
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'chat.message',
                    'message': message,
                    'username': username,
                    'user_picture': user_picture,
                    'time_stamp': time_stamp,
                }
            )
        else:
            # Handle the case where the VirtualRoom does not exist
            print(f"VirtualRoom with slug '{self.room_name}' does not exist.")

    @database_sync_to_async
    def save_interaction_to_database(self, user_id, virtual_room, message):
        # Save the message to the database with the VirtualRoom instance
        Interaction.objects.create(
            user_id=user_id,
            room_name=virtual_room,
            content=message
        )

    @database_sync_to_async
    def get_old_messages(self, virtual_room):
        # Fetch old messages based on the VirtualRoom
        return list(Interaction.objects.filter(room_name=virtual_room).order_by('time_stamp').values('user', 'content'))

    @database_sync_to_async
    def get_username(self, user_id):
        try:
            user = User.objects.get(id=user_id)
            return user.username
        except User.DoesNotExist:
            return None

    @database_sync_to_async
    def get_user_profile_picture(self, user_id):
        try:
            user = User.objects.get(id=user_id)

            # Check if the user has a profile picture
            if hasattr(user, 'user_picture') and user.user_picture:
                user_picture = user.user_picture
                # Use Django storage to get the correct file path
                image_path = user_picture.path
                if os.path.isfile(image_path):
                    # Return the actual user picture URL if the image file exists
                    return user_picture.url
                else:
                    # Log that the image file doesn't exist and return the default avatar
                    print(f"Image file for user {user_id} does not exist. Using default avatar.")
                    return static('images/avatar.svg')
            else:
                # Log that the user does not have a profile picture and return the default avatar
                print(f"User {user_id} does not have a profile picture. Using default avatar.")
                return static('images/avatar.svg')

        except User.DoesNotExist:
            # Log that the user does not exist and return the default avatar
            print(f"User {user_id} does not exist. Using default avatar.")
            return static('images/avatar.svg')

    @database_sync_to_async
    def get_virtual_room(self):
        try:
            return VirtualRoom.objects.get(slug__iexact=self.room_name)
        except VirtualRoom.DoesNotExist:
            return None

    # Receive message from the room group
    async def chat_message(self, event):
        message = event['message']
        username = event['username']
        user_picture = event['user_picture']
        time_stamp = event['time_stamp']

        print(f"Sending message with timestamp: {time_stamp}")
        # Send the message to WebSocket
        await self.send(text_data=json.dumps({
            'message': message,
            'username': username,
            'user_picture': user_picture,
            'time_stamp': time_stamp,
        }))




and this is my frontend:


<!DOCTYPE html>
{% load static %}
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{% static 'css/discussionroom.css' %}">
    <title>Discussion Room</title>
</head>
<body>
<div id="discussion-room">
    <div id="chat-box">
    {% for message in messages %}
        <div>
            <img src="{{ message.user_picture.url|default:'/static/images/avatar.svg' }}" alt="User Picture" style="width: 30px; height: 30px;">
            <strong>{{ message.username }}:</strong>
            {{ message.message }}
            <span class="timestamp">{{ message.time_stamp|timesince }}</span>
        </div>
    {% endfor %}
    </div>
    <input type="text" id="message-input" placeholder="Type your message...">
    <button onclick="sendMessage()">Send</button>
</div>

<script>
    // Get the room name from the URL
    const pathArray = window.location.pathname.split('/');
    const roomNameIndex = pathArray.indexOf('discussions') + 1;
    const roomName = pathArray[roomNameIndex].split('@')[1];

    // Log the extracted room name
    console.log('Extracted room name:', roomName);

    // Create a new WebSocket connection
    const socket = new WebSocket(`ws://${window.location.host}/ws/discussions/${roomName}/`);

    socket.onmessage = function(event) {
        const data = JSON.parse(event.data);
        console.log('Received data:', data);
        displayMessage(data.user_picture, data.username, data.message, data.time_stamp);
        // Save timestamp to local storage
    localStorage.setItem('lastTimestamp', data.time_stamp);
};
    

    
    

    function sendMessage() {
        const message = document.getElementById('message-input').value;
        if (message.trim() !== '') {
            socket.send(JSON.stringify({'message': message}));
            document.getElementById('message-input').value = '';
        }
    }

    
    function displayMessage(userPicture, username, message, timestamp) {
        console.log('Received timestamp:', timestamp);
        console.log('Received user picture:', userPicture);
     localStorage.setItem('lastTimestamp', timestamp);

    const messageDiv = document.createElement('div');

    // Set the userPicture URL
    const imageUrl = userPicture || '/static/images/avatar.svg';

    //console.log('Selected image URL:', imageUrl);

    const imgElement = new Image();
    imgElement.src = imageUrl;

    // Add an event listener to handle image load errors
    imgElement.addEventListener('error', function() {
        //console.warn('Error loading image. Using default avatar.');
        messageDiv.innerHTML = `<img src="/static/images/avatar.svg" alt="Default Avatar" style="width: 30px; height: 30px;"> ${message}`;
        document.getElementById('chat-box').appendChild(messageDiv);
    });

    // Add an event listener to handle image load success
    imgElement.addEventListener('load', function() {
        imgElement.className = 'user-profile-img'; // Add this line
        messageDiv.innerHTML = `<img src="${imageUrl}" alt="User Picture" style="width: 30px; height: 30px;  border-radius: 50%; object-fit: cover; "> <strong>${username}:</strong> ${message}`;
        document.getElementById('chat-box').appendChild(messageDiv);
    });
}
const storedTimestamp = localStorage.getItem('lastTimestamp');
if (storedTimestamp) {
    console.log('Retrieved timestamp from local storage:', storedTimestamp);
}
</script>

</body>
</html>

Open file from a reference in Browser. Using JS or ReactJS – Should work for all major browsers

One of the requirements I have is to create a link on website which will pop open the file when the link is clicked. Eg. LinkName: CustomerDetails.xml Location: C:/product/customer/details/Customer.xls

This file should open when the link CustomerDetails is clicked. It should not bring the contents in the browser itself but should just pop open the file ( Like clicking the file in windows folder ).

How to do this using reactJS or Javascript.

Thanks

JS Function in a object [closed]

If we don’t write the word functionbefore defining a function inside an object, will it work?

Ans please………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………

javascript event.preventDefault() is not working

I’m creating a website for sign in and sign up, but event.preventDefault() doesn’t seem to work well. It works fine on the sign up button, but it refreshes every time I press the sign in button. Uncaught TypeError: Cannot read property ‘addEventListener’ of null
At window.onload (firebase.js:27) error, I think the code is loaded. What should I do?

  1. event.preventDefault() is not working on Sign in button(Every time I press it, it refreshes page)
  2. BUT it works well on Sign up button
  3. they are same submit buttons

Below are my codes.

index.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="postArchive" content="postArchive Login Page">
  <meta name="description" content="postArchive Login Page">
  <meta name="author" content="leeyunseokarchive">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  <title>postArchive</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
  <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@100;300;400;500;700;900&display=swap"
    rel="stylesheet">
</head>

<body>
  <form>
    <h1>Login</h1>
    <div>
      <input type="email" id='signInEmail' placeholder="Email" />
    </div>
    <div>
      <input type="password" id='signInPassword' placeholder="Password" />
    </div>
    <button type="button" onclick="location.href='signUpPage.html'">Sign up</button>
    <button type="submit" id='signInButton'>
      Login
    </button>
  </form>

  <script type="module" src="firebase.js"></script>
  <script src="script.js"></script>
</body>

</html>

signUpPage.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="postArchive" content="postArchive Sign Up Page">
  <meta name="description" content="postArchive Sign Up Page">
  <meta name="author" content="leeyunseokarchive">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  <title>postArchive</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
  <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@100;300;400;500;700;900&display=swap"
    rel="stylesheet">
</head>

<body>
  <form>
    <h1>Sign Up</h1>
    <button type="button" onclick="location.href='index.html'">
      < </button>
        <div>
          <input type="email" id='signUpEmail' placeholder="Email" />
        </div>
        <div>
          <input type="password" id='signUpPassword' placeholder="Password" />
        </div>
        <button type="submit" id='signUpButton'>
          Submit
        </button>
  </form>

  <script type="module" src="firebase.js"></script>
  <script src="script.js"></script>
</body>

</html>

firebase.js

// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.8.1/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/10.8.1/firebase-analytics.js";
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/10.8.1/firebase-auth.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "AIzaSyCzIYEq71SHZWRCIyLdJ6IsJKxH40QYiek",
  authDomain: "postarchive.firebaseapp.com",
  projectId: "postarchive",
  storageBucket: "postarchive.appspot.com",
  messagingSenderId: "688294967718",
  appId: "1:688294967718:web:2fe5548a7327f12f7b3767",
  measurementId: "G-G16DKM4G12"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const auth = getAuth();

//sign up
document.getElementById('signUpButton').addEventListener("click", (event) => {
  event.preventDefault()
  const signUpEmail = document.getElementById('signUpEmail').value
  const signUpPassword = document.getElementById('signUpPassword').value

  createUserWithEmailAndPassword(auth, signUpEmail, signUpPassword)
    .then((userCredential) => {
      console.log(userCredential)
      // Signed up
      const user = userCredential.user;
      // ...
    })
    .catch((error) => {
      console.log('sign up error')
      const errorCode = error.code;
      const errorMessage = error.message;
      // ..
    });

})
//sign in
document.getElementById('signInButton').addEventListener("click", (event) => {
  event.preventDefault()
  const signInEmail = document.getElementById('signInEmail').value
  const signInPassword = document.getElementById('signInPassword').value

  signInWithEmailAndPassword(auth, signInEmail, signInPassword)
    .then((userCredential) => {
      // Signed in
      console.log(userCredential)
      const user = userCredential.user;
      // ...
    })
    .catch((error) => {
      console.log('sign in error')
      const errorCode = error.code;
      const errorMessage = error.message;
    });

})

i want to solve this problem 🙁

Randomly generated number makes certain button highlighted

I’m building my first JS project and I want to generat a number from 1-100 and to add black border to one of 5 rectangles each representing a range of numbers (0-20, 20-40, etc). Unfortunately, the rectangles are highlighted randomly and don’t appear to be tied to the generated number

Here what I wrote. How do I make this work properly?

const makeNumber = () => {
  const randomValue = Math.trunc(Math.random() * 100 + 1);
  return randomValue;
};

test.addEventListener("click", function() {
  h1.innerText = makeNumber();
  statValue();
});

function remove() {
  stat.forEach((stat) => {
    stat.classList.remove("my-class");
    gif.style.visibility = "hidden";
  });
}

function statValue() {
  if (makeNumber() <= 20) {
    remove();
    normal.classList.add("my-class");
  } else if (makeNumber() > 20 && makeNumber() <= 40) {
    remove();
    stable.classList.add("my-class");
  } else if (makeNumber() > 40 && makeNumber() <= 60) {
    remove();
    warning.classList.add("my-class");
  } else if (makeNumber() > 60 && makeNumber() <= 80) {
    remove();
    overload.classList.add("my-class");
  } else if (makeNumber() > 80) {
    remove();
    critical.classList.add("my-class");
    gif.style.visibility = "visible";
  }
}
.my-class {
  border: 3px solid black;
}
<div class="container">
  <div class="meter">
    <div class="stat normal"></div>
    <div class="stat stable"></div>
    <div class="stat warning"></div>
    <div class="stat overload"></div>
    <div class="stat critical"></div>
    <img class="gif" src="img/Blinking_warning.gif" alt="">
  </div>

  <h1>0</h1>
  <button class="btn">test</button>

</div>

how to make animation init itself whenever clicking a button in Web Programming

I want to make a react component initiates the animation whenever I click it. There are some options:

  1. if i change the props at middle of the animation, it should re-animate form the start.
  2. changing of the props is triggered by a button of another node.

here’s my code i tried:

function Button() {
  const indexRef = useRef(0);
  const clickHandler = () => {
    indexRef.current++;
  }
  return (<button onClick={clickHandler}><SkillWindow data={somedata[indexRef]}/></button>)
}

interface SkillWindow extends DefaultProps {
  data: SkillData;
}
function SKillCard({ data, className }: SkillWindow) {
  const id: string = "skillcard--0";
  useEffect((): void => {
    const target: HTMLElement | null = document.getElementById(id);
    if (!target) return;
    target.addEventListener("click", (): void => {
      target.style.animationPlayState = "paused";
    });
    target.style.animation = "running";
  }, [data]);
  const { name, desc }: SkillData = data;
  const style: TailwindProperties = {
    xl: "xl:w-96 xl:ml-8  xl:pb-8  xl:flex xl:flex-col xl:items-center xl:gap-8",
    base: "bg-neutral-200 bg-opacity-75 _swash-in",
  };
  return (
    <section className={`${style.xl} ${style.base} ${className}`} id={id}>
      <WindowPanel />
      <div className="w-40 h-40 rounded-full bg-black" />
      <div className="flex flex-col gap-4 items-center">
        <h1 className="text-lg font-bold">{name}</h1>
        <h2 className="text-base font-normal">hello</h2>
        <p className="text-base font-normal">{desc}</p>
      </div>
    </section>
  );
}
export default SKillCard;

TypeError: Cannot set properties of null in plain Javascript

I’m trying to make a counter with JavaScript. But I seem to get this error.

error:TypeError: Cannot set properties of null (setting ‘textContent’)

$ node “c:UsersUSERDesktopJavaScript Projectsjavascript-basic-projects-master2-countersetupapp.js”
c:UsersUSERDesktopJavaScript Projectsjavascript-basic-projects-master2-countersetupapp.js:5const value = document.querySelector(“value”);
^

ReferenceError: document is not defined
at Object. (c:UsersUSERDesktopJavaScript Projectsjavascript-basic-projects-master2-countersetupapp.js:5:15)
at Module._compile (node:internal/modules/cjs/loader:1254:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
at Module.load (node:internal/modules/cjs/loader:1117:32)
at Module._load (node:internal/modules/cjs/loader:958:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47

Node.js v18.16.0

#app.js

// Set initial count
let count = 0;

// Select vaues and buttons
const value = document.querySelector("value");
const btns = document.querySelectorAll(".btn");

btns.forEach(function (btn) {
  btn.addEventListener("click", function (e) {
    const styles = e.currentTarget.classList;
    if (styles.contains("decrease")) {
      count--;
    }
    value.textContent = count;
  });
});

#index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Counter</title>

    <!-- styles -->
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
<div class="container">
  <h1>
    Counter
  </h1>
  <span id="vale">0</span>
  <div class="button-container">
    <button class=" btn decrease">decrease</button>
    <button class="btn reset">reset</button>
    <button class="btn increase">increase</button>
  </div>
</div>
    <!-- javascript -->
    <script src="app.js"></script>
  </body>
</html>

Why does my Chrome extension code work when inspecting elements, but not otherwise?

I’m currently developing a Chrome extension where I attempt to fast-forward to a specific minute. Strangely, when I manually inspect the element and extend it through the developer tools, my code works as intended. However, without manually inspecting and extending the element, it throws an error.

I’m curious about the underlying reason for this behavior. Could someone shed light on why inspecting the element makes my code functional, while it fails otherwise?

This is the error message when not expanding

otherwise it overtakes without problems

Need a reload for SocketIO to connect properly in my Project

I am developing my personal project and I did everything with convention but I still got a bug that most of the times I need to reload the Page where socket is called to work properly.
GitHub
Deployed App
Problem Video Here it stuck on loading page after exiting sometimes this happens when you just join a room.
But if you reload when you are stuck at loading page it works fine.

I tried to check what went wrong and after spending my midnight oil I logged my socket in my client






export const initSocket = () => {



    return io(BACKEND_URL, {



        reconnectionAttempts: 5,



        transports: ["websocket"],



    })



}

There when things worked fine socket gives connected true but if not false. Please help me with the issue and pls watch the video for the issue.

related to js image slider….Can anyone tell me why is it not working properly

const N = document.querySelector(‘.right’)

const P = document.querySelector(‘.left’)

const slider = document.querySelector(‘.slider’)

//Number of images are 3
//with to slider buttons

let slideno = 1

N.addEventListener(‘click’, () => {

if (slideno {

if (slideno > 3) {
slider.style.transform = `translateX(0px)`
slideno = 1
} else {
slider.style.transform = `translateX(785px)`
slideno–
}
})

//In this program it worked great during next slides but not in reverse movement can anyone guide me what m i doing wrong?