Blazor WASM – JS(rive app) is not being re-rendered after default navigating

I have issue with re-rendering rive animation after I leave default page “/”. When I return back (/counter -> /) animation is not displayed anymore but js modul is being called in the code so I am not sure how can I deal with this problem.

here is a code:

Index.razor->

@page "/"
@inject IJSRuntime JSRuntime

<canvas id="canvas" width="500" height="500"></canvas>

@code {
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./Pages/Index.razor.js");
        }
    }
}

Index.razor.js ->

const r = new rive.Rive({
    src: 'bear.riv',
    canvas: document.getElementById('canvas'),
    autoplay: true,
    })

Index.html ->

    <script src="_framework/blazor.webassembly.js"></script>
    <script src="https://unpkg.com/@rive-app/[email protected]"></script>

Any advice would be much appreciated. Thank you!

Allow website display but restrict access if in direct URL

I’ve been looking for the right solution but I can’t find any.
My goal is to allow it to be embedded/displayed in the website but not allowed to be accessed directly via URL.

I understand that it can be done via .htaccess but the files are not fixed and will depend on the upload of the users.

This is an example. Even when not logged in, it can be accessed.

I found a similar question but unanswered as well.

Any help is highly appreciated!

Method to add an element via innerHTML

const myElement = document.createElement("div");
let selectItems = data.map((select, i) => (
    `<div class="select">
        <div aria-required="true" class="selectBtn" data-type="">${select.placeholder}</div>    
            <div class="selectDropdown">${select.option.map(el =>
                    `<div class="option" data-type="firstOption">${el}</div>`
            ).join('')}
        </div>
    </div>`)
)

const eles = document.getElementsByClassName("select");
for (let i = 0; i < eles.length; i++) {
    myElement.innerHTML = selectItems[i]; ///loop
    eles[i].appendChild(myElement.cloneNode(true));
}

I’m trying to add elements through a loop but an infinite loop occurs

Javascript – Scope question and how can i reset all numbers in my game?

i am working on a numbers click game. The idea of the game is you get a random pattern of numbers and you have to click those numbers in order (this hasn’t been implemented yet). Game also has a function for random numbers, random colors and random font sizes. I have 2 questions:

  1. If you look at my comments in JS file, basically i created a variable called “timeInterval” for my setInterval function. When you scroll down to the bottom, in my resetBtn.EventListener, i am able to clearInterval(timeInterval) and it works. Why does this work? I thought in order for this to work, first i would have to declare timeInterval as a global var or let variable in the global scope? The fact that its inside my startGame() function and i am able to execute it in my resetBtn.EventListener function doesn’t register with me. How am i executing it without it being declared globally? What am i missing?

  2. I am working on my reset button at the moment. I am trying to reset all my numbers either to 0 or to a blank state in all of my squares (i also want to do that to font, color etc). From my understanding in order to do that i need to take squares[i].textContent and set that to 0. Being that squares[i].textContent is inside a loop of my randomNumber() function, im having a hard to of how i can access that property. Any help would be appreciated.

Sorry for so much writing, i tried to put my thoughts out there so maybe someone can catch an error in my thinking or what i am interpreting wrong.

Thank you so much. Here is the code:

HTML

 <body>
    <main>
      <div class="time">
        <p class="time__countdown">Time left: 60</p>
      </div>
      <grid class="grid">
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
      </grid>
      <div class="buttons">
      <button class="btn start-btn">Start Game</button>
      <button class="btn reset-btn">Reset Game</button>
      </div>
    </main>

    <script src="index.js"></script>
  </body>

CSS

* {
    margin: 0;
    padding: 0;
    }
    
    body, html {
    min-width: 100%;
    min-height: 100vh;
    box-sizing: border-box;
    font-size: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: black;
    }
    
    
    img {
        max-width: 100%;
        display: block;
    }

   
    main {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        width: 24%;
        background-color: white;
        border-radius: 10px;
    }

    .grid {
        border: 2px solid black;
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        background-color: white;
        justify-content: center;
        align-items: center;
        gap: 2px;
        padding-top: 3px;
        padding-bottom: 3px;
        
       
        
    }

    .square {
        border: 2px solid black;
        width: 70px;
        height: 70px;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .time {
        padding-bottom: 2em;
        padding-top: 1em;
    }

    .btn {
        margin: 1em;
    }

    .buttons {
        display: flex;
    }

JAVASCRIPT


// randomzie numbers
// randomize font size
// Randomzie colors 
// change background when clicking
let startBtn = document.querySelector('.start-btn')
let resetBtn = document.querySelector('.reset-btn')
let timer = document.querySelector('.time__countdown')
const squares = [...document.querySelectorAll('.square')];
let gameStarted = false;
let counter = 60









startBtn.addEventListener('click', startGame)


function startGame() {
gameStarted = true;

    if (gameStarted === true) {
        for (let i = 0; i < squares.length; i++) {
            squares[i].addEventListener('click', function() {
                squares[i].style.backgroundColor = 'lightgreen'
            }) 
        } 
    }
    randomNumber() 
// This timeInterval below is not declared globally, its inside startGame() (scroll down to resetBtn.EventListener)
   timeInterval = setInterval(function () {
        counter--
        if (counter >= 0) {
            timer.innerHTML = `Time left: ${counter}`
        }
    }, 1000)
}  

       
function getRandomColor() {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
  }
  


function randomNumber() {
  
    for (let i = 0; i < squares.length; i++) {
        const random = Math.floor(Math.random() * 25)
        squares[i].textContent = random
        squares[i].style.fontSize = random + 15 + "px";
        squares[i].style.color = getRandomColor()
        squares[i].style.backgroundColor = '#1F2937'
}


}

resetBtn.addEventListener('click', function() {
    clearInterval(timeInterval) 
    counter = 60
    // Why does timeInterval work here via scope when timeInterval function is inside startGame() and not declared globally??
    timer.innerHTML = `Time left: 60`
    

})

JS – how to replace an object with spread operator AND condtion?

I have an array of objects.
I need to:

  • check if the object has a specific key:value combination
  • if yes, replace a different value of this object
  • return both the objects

This is how I am trying to achieve it:

list.map(item => {
          return {
            ...item,
            ...(item["orderId"] === 'xyz' && { transactionNumber: 'sadfdas gasdgas' }),
          }

I also tried this condition instead:

...(orderId === 'xyz' && { transactionNumber: 'sadfdas gasdgas' })

and this:

...(item.orderId === 'xyz' && { transactionNumber: 'sadfdas gasdgas' })

However they all return the two objects in the list unchanged.

If I instead use this code:

.map(item => {
  return {
    ...item,
  transactionNumber: 'sadfdasgasdgas' 
  }
})

it replaces the transactionNumber for each object.

What am I doing wrong that the condition is not working?

Why does my try/catch not work when autoplay is blocked?

(function() {
    const music = new Audio('assets/sounds/music.mp3');

    try {
        music.play();
    } catch(err) {
        alert('Please allow autoplay! ' + err);
    }
})()

I have introduced a try/catch block when attempting to play a sound because if autoplay is blocked the code will return an error. Although the code is inside try {..} it still returns an error.

I have read on some old posts as well as other websites that try/catch blocks only catch runtime errors. This article says ‘A runtime error occurs while a program is running or when you first attempt to start the application.’

I am not sure why all this happening, can someone explain??

Not able to position 4th element in second row using css grid

Problem – I want to keep the 4th box in 2nd row like in the current code, but the width of the 4th box should be similar to 1/2/5/6 box i.e. 100px.

But currently 4th box is taking full width in 2nd row, I want it to take only 100px space and rest empty space in row 2. 5 and 6 ox should come on 3rd row.

Alignment Needed –

1 2 3
4
5 6
7 7 7

Code –

.one { background: red; }
.two { background: green; }
.three { background: blue; }
.four { background: pink; }
.five { background: violet; }
.six { background: yellow; }
.seven { background: teal; }
.box { padding: 5px; text-align: center; }
.container {
  border: 1px solid;
  display: grid;
  grid-template-columns: 100px 100px auto;
  gap: 20px 10px;
}

.box:nth-child(4) {
  grid-column: span 3;
}

.box:last-child {
  grid-column-end: span 3;
}
<div class="container">
  <div class="box one">1</div>
  <div class="box two">2</div>
  <div class="box three">3</div>
  <div class="box four">4</div>
  <div class="box five">5</div>
  <div class="box six">6</div>
  <div class="box seven">7</div>
</div>

!== working but === not working within function in typescript

Why === NOT WORKING whereas !== is working within function in typescript?

const a = [{id: 4, name: 'Greg'}, {id: 1, name: 'David'}, {id: 2, name: 'John'}, {id: 3, name: 'Matt'}, ]; 
const b = [ {id: 5, name: 'Mathew', position: '1'}, {id: 6, name: 'Gracia', position: '2'}, {id: 2, name:        'John', position: '2'}, {id: 3, name: 'Matt', position: '2'}, ];

const s = a.filter(({ id: idv }) => b.every(({ id: idc }) => idv !== idc));
console.log(s);

const r = a.filter(({ id: idv }) => b.every(({ id: idc }) => idv === idc));
console.log(r);

Foreach according to collection attribute

I have a existing laravel project on php 7.4.

It has users table, patient_appointmnets table.

In users table it contains both patient and doctor with role_id
And there is a doctor_details table which contain only basic info.

The patient_appointments table has
user_id, doctor_id, date, start_time and end_time

The problem is if do

PatientAppointment:whereDate('date', Carbon:now()->format('Y-m-d')->get() ;

And use foreach in blade

I get appointments wise column.
So e.g if a doctor has multiple appointments on that day. I got same doctor column multiple times.

But i want all appointments go in single column for particular dooctir id.
There is no direct doctor tablebwhich contains appointment. On patient_appointmnets table has doctor_id and user_id

So i want collection according to doctor where it contains all appintment

I could do join like:

 $var =  DoctorDetail:join('users.id', '=', 'doctor_derail.user_id')->select('doctor_detail.*')->get();

then,

for(i=0; i <= count($var) ; i++)
{
    $var[$i->appointments] = PatientAppointment::whereDate('date', Carbon::now()->format('Y-m-d')->get();
}

 return $var;

but not work. But in dd it show appointments inside doctor_detail collection. But if i do foreach in blade, it shows builder:get() expects 1 for very first get() query..

Any other solution to do same thing.

How do I call a function inside a forEach loop inside a class method Javascript?

I have a function inside a class method that in unread when being called into a forEach loop.

// class method
Graph() {
  function setKey(key) {
    let setKeyStack = [key];
    return setKeyStack;
  }

  // forEach loop
  this.vertices.forEach((e) => {
    if (e === s) {
      const keyToAdd = this.nodeIDS + this.nodeIdCount.toString();
      e.setKey // not being called
    }
)

I tried attaching it to a this key word

this.setKey = setKey

but you cannot use the this keyword to attach variables to functions

ex: e.this.setKey(something)// not possible

jQuery Timeago Library Setup

I have been triying to set-up the timeago library but haven’t been able to get it working. Any help is appreciated.

In my project directory I have lib/timeago.js.

In my index.html I have<script src="lib/timeago.js" type="text/javascript"> </script>

In my my app.js I have $(document).ready(function() { $("time.timeago").timeago();

I also have:

var $timestamp = $('<time class="timeago timestamp">July 17, 2008</time>');
$timestamp.attr("datetime", tweet.createdAt.toISOString());
$timestamp.appendTo($tweet);

tweet.createdAt is set to new Date();.

However, when I display the elements I can only view the text “July 17, 2008”. If I remove that I cannot see anything. Does anyone know how I might fix this?

Increment number in text field of a specific field

When the #addHoursBtn is clicked, the value in the textfield of that specific row should increase.
I can’t figure out how I can select that specific textfield.

Can anyone help me?

let i = 0;

for (const [key, value] of Object.entries(y)) {
  let htmlString = `<tr><td>${key}</td><td>${value.studiepunten}</td> <td>${value.belasting}</td> <td class='spacer'><input type='text' id="input-course${i}" name="hourfield" value="" readonly><button id="course${i}" class='myButton smlBtn' value='&#x2b;'>&#x2b;</button></td><td><input id="clearRowBtn" type="submit" class="myButton smlBtn delBtn" value="&#xf1f8;"></td></tr>`;
  i++;
  document.querySelector("#t-body").innerHTML += htmlString;
  //console.log(htmlString);
}

for (let index = 0; index < i; index++) {
  let selector = "#course" + index;
  console.log(selector);
  document.querySelector(selector).addEventListener("click", (e) => {
    console.log("button has been clicked", e);
  });
}

document
  .querySelector("#addHoursBtn")
  .addEventListener("click", increaseCounter);
function increaseCounter() {
  let count = Number(window.localStorage.getItem("count"));
  count += 1;
  window.localStorage.setItem("count", count);
  document.getElementById("#course" + index).value = count;
}

I tried to select the specific textfield by .getElementById(“#course” + index)
It’s not working.
I also tried to select the textfield by using the selector variable, doesn’t work.

How to have different CSS components for each paragraph in my interactive website

The user is able to click anywhere on the screen and the paragraphs are printed out one by one in the mouse location that the user chooses. However I want to have these paragraphs in different styles so my question is, how do I have different css elements for each paragraph in the array?
Any help would be much appreciated.

const texts = [
  "Paragraph: 1",
  "Paragraph: 2",
  "Paragraph: 3",
  "Paragraph: 4",
  "Paragraph: 5",
  "Paragraph: 6",
  "Paragraph: 7",
  "Paragraph: 8",
  "Paragraph: 9",
  "Paragraph: 10"
];

// Keeps Track of Current Text
let currentParaIdx = 0;

document.addEventListener("click", (e) => {
  // Stop once All Texts are Displayed
  if (currentParaIdx === texts.length) return;

  const { clientX, clientY } = e; //get the click position

  //create the div
  const div = document.createElement("div");

  //set its text
  div.innerText = texts[currentParaIdx];
  currentParaIdx++;

  //set its position and position style
  div.style.position = "absolute";
  div.style.left = clientX + "px";
  div.style.top = clientY + "px";

  document.body.append(div); //add div to the page
});

This is my code so far so how can I incorporate css into these individual paragraphs?

how can I create two buttons for two different options that are being selected from a scripting code?

In the image bellow you can see a variant selector that lets me choose between sizes and colors.
There is also a name to them (Color & Size) displayed right above each selection.

enter image description here

I would like to replace those title’s with button that open a Color guide and a Size guide. I got the buttons but I don’t know how to place the, correctly so that this works.

Now the complicated part comes into play.

These two options (color & size) are created by a scripting code I believe. (view next picture).

enter image description here

As you can see on line 488 there is a legend with a text of {{option.name}}. This Option name is the name color & size. The name can be sethere. ( view next picture).

enter image description here

It’s a bit hard to explain but basically if a option is set the {{option.name}} from picture 2 will enter the value from Option name from picture 3 and create a variant selector (you can create as many as you like). Everytime you create a new option the whole thing fro, picture number 2 gets duplicated (only in online view).

I tried to put a html button inside the option name of picture 3 but this happened. (picture number 4)

enter image description here

it start displaying all of this values as text: (picture number 5)

enter image description here

Currently I got two Idea’s.

Idea number 1:

Change the legend to a button make a onclick function that uses the {{option.name}}() as onclick.

Idea number 2:

use an Id to called {{option.name}} and display size guide button if the id = “Size” and display color guide if id = “Color”. This method didn’t really worked because it displayed Size guide if the id was size but it displayed it for both of the variant selectors.

Please ask if there are any questions. I might missed some important information for you because I don’t know anything about scripting etc.

Thanks in advance!