How to display new chat messages immediately without reloading the whole page?

Alright, first question here!
I’m writing a chat application and what i need is for new messages to be displayed immediately, not just after a reload. I don’t know the best way to go about this; maybe reload just the chat-message-container again? Or display new messages as their own chatMessage elements? In either case I wouldn’t know how to do it.
I commented in the JS where I think the required logic needs to be. Any help is much appreciated!!

The HTML and JS:

{% extends "main.html" %} {% block content %}
<main class="messagePage my-xl">
  <div class="content-box">
    <div class="chat-header">
      <a class="backButton" href="{% url 'inbox' %}"><i class="fa-solid fa-arrow-left"></i></a>
      <h1 class="username-top">{{ other_user.username }}</h1>
    </div>

    <div class="chat-message-container">
      {% for chat_message in chat_messages %}
      <div
        class="chatMessage{% if chat_message.sender == profile %} chatMessage--right{% else %} chatMessage--left{% endif %}"
        id="chat-messages">
        <small>{{ chat_message.content|safe }}</small>
      </div>
      {% endfor %}
    </div>

    <div class="chat-bottom-section">
      <form method="post" action="" class="chat-form">
        {% csrf_token %}
        <div class="chat-input">
          <input
            type="text"
            name="content"
            class="flex-1 mr-3"
            placeholder="Your message..."
            id="chat-message-input"
          />
          <button id="chat-message-submit">
            <span class="icon-btn material-symbols-outlined">send</span>
          </button>
        </div>
      </form>
    </div>
  </div>
</main>
{% endblock %} 
{%block script%} 
{{ room.id|json_script:"json-room-id" }} 
{{profile.id|json_script:"json-sender-id" }} 
{{other_user.id|json_script:"json-receiver-id" }}

<script>
  const roomId = JSON.parse(
    document.getElementById("json-room-id").textContent
  );
  const senderId = JSON.parse(
    document.getElementById("json-sender-id").textContent
  );
  const receiverId = JSON.parse(
    document.getElementById("json-receiver-id").textContent
  );
  const chatSocket = new WebSocket(
    "ws://" + window.location.host + "/ws/" + roomId + "/"
  );

  chatSocket.onopen = function (e) {
    console.log("yas bitch");
  };

  chatSocket.onclose = function (e) {
    console.log("onclose");
  };

  chatSocket.onerror = function (e) {
    console.error("WebSocket error:", e);
  };

  chatSocket.onmessage = function (e) {
    try {
      const data = JSON.parse(e.data);
      /*logic to append new messages/reload the css element*/
      scrollToBottom();
    } catch (error) {
      console.error("Error parsing WebSocket data:", error);
    }
  };

  document.querySelector("#chat-message-input").focus();
  document.querySelector("#chat-message-input").onkeyup = function (e) {
    if (e.keyCode === 13) {
      e.preventDefault();
      document.querySelector("#chat-message-submit").click();
    }
  };

  document.querySelector("#chat-message-submit").onclick = function (e) {
    e.preventDefault();

    const messageInputDom = document.querySelector("#chat-message-input");
    const message_content = messageInputDom.value;

    console.log({
      message_content: message_content,
      senderId: senderId,
      receiverId: receiverId,
      roomId: roomId,
    });

    chatSocket.send(
      JSON.stringify({
        message_content: message_content,
        senderId: senderId,
        receiverId: receiverId,
        roomId: roomId,
      })
    );

    messageInputDom.value = "";

    return false;
  };



  function scrollToBottom() {
    let objDiv = document.getElementById("chat-messages");
    objDiv.scrollTop = objDiv.scrollHeight;
  }
  scrollToBottom();

</script>
{%endblock%}

The view:

@login_required(login_url="login")
def private_chat_view(request, pk):
    profile = request.user.profile
    room = Room.objects.get(id=pk)
    other_user_profile = room.get_partner(profile)
    chat_messages = room.messages.all().reverse()
    
    for chat_message in chat_messages:
        chat_message.content = insert_line_breaks(chat_message.content)

    return render(request, 'chats/room.html', {
        'chat_messages': chat_messages,
        'room': room,
        'profile': profile,
        'other_user': other_user_profile
    })

I tried both approaches I previously mentioned, in both cases nothing happened.

Is there a way I can write my js code in fewer lines to make it cleaner?

I’m new to javasript and i’m trying to create a border radius reviewer where the border radius of the four sides of a rectangle changes based on the values entered into the four textboxes linked to each edge. This is my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Border-radius previewer</title>
<style>
body, .outer-square{
    background-color: white;
    display: flex;
    justify-content: center;
    align-items: center;
}

.inner-square{
    border: 1px solid #000;
    width: 400px;
    height: 200px;
    background-color: rgb(255, 255, 255);
}

.outer-square{
    border: 1px solid #000000;
    width: 500px;
    height: 300px;
    background-color: rgb(211, 200, 200);
    border-top-left-radius: 0px;
    border-top-right-radius: 0px;
    border-bottom-left-radius: 0px;
    border-bottom-right-radius: 0px;
    margin-top: 100px;
}

input{
    width: 10px;
}

p{
    margin-left: 10px;
}
 </style>
</head>
<body>
    <div class="outer-square" id="outer-square">
        <div class="inner-square" id="inner-square">
            <p id="top-left-output"></p>
            <p id="top-right-output"></p>
            <p id="bottom-left-output"></p>
            <p id="bottom-right-output"></p>
        </div>
    </div>
    <input type="text" id="top-left-border-radius" value="0">
    <input type="text" id="top-right-border-radius" value="0">
    <input type="text" id="bottom-left-border-radius" value="0">
    <input type="text" id="bottom-right-border-radius" value="0">
<script>
const innerSquare = document.getElementById('inner-square')
const outerSquare = document.getElementById('outer-square')

//Inputs
const topLeftInput = document.getElementById('top-left-border-radius')
const topRightInput = document.getElementById('top-right-border-radius')
const bottomLeftInput = document.getElementById('bottom-left-border-radius')
const bottomRightInput = document.getElementById('bottom-right-border-radius')

//This section contains declaration of output
const top_left_output = document.getElementById('top-left-output')
const top_right_output = document.getElementById('top-right-output')
const bottom_left_output = document.getElementById('bottom-left-output')
const bottom_right_output = document.getElementById('bottom-right-output')


//Adding event listeners
topLeftInput.addEventListener('input', function(e){
    top_left_output.textContent = `border-top-left-radius: ${topLeftInput.value}px;`
    outerSquare.style.borderTopLeftRadius = `${topLeftInput.value}px`
})

topRightInput.addEventListener('input', function(e){
    top_right_output.textContent = `border-top-right-radius: ${topRightInput.value}px;`
    outerSquare.style.borderTopRightRadius = `${topRightInput.value}px`
})

bottomLeftInput.addEventListener('input', function(e){
    bottom_left_output.textContent = `border-bottom-left-radius: ${bottomLeftInput.value}px;`
    outerSquare.style.borderBottomLeftRadius = `${bottomLeftInput.value}px`
})

bottomRightInput.addEventListener('input', function(e){
    bottom_right_output.textContent = `border-bottom-right-radius: ${bottomRightInput.value}px;`
    outerSquare.style.borderBottomRightRadius = `${bottomRightInput.value}px`
})
    </script>
</body>
</html>

This code roughly does what i want but i believe i should be able to do this in fewer ines of code. I was able to come up with this but i was not able to add the texts within the div with the data attribute “output”.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Border-radius previewer</title>
<style>
    body, .outer-square{
    background-color: white;
    display: flex;
    justify-content: center;
    align-items: center;
}

.inner-square{
    border: 1px solid #000;
    width: 400px;
    height: 200px;
    background-color: rgb(255, 255, 255);
}

.outer-square{
    border: 1px solid #000000;
    width: 500px;
    height: 300px;
    background-color: rgb(211, 200, 200);
    border-top-left-radius: 0px;
    border-top-right-radius: 0px;
    border-bottom-left-radius: 0px;
    border-bottom-right-radius: 0px;
    margin-top: 100px;
}

input{
    width: 10px;
}

div{
    margin-left: 10px;
}
</style>
</head>
<body>
    <input type="text" data-border-radius="top-left-border-radius" value="0">
    <input type="text" data-border-radius="top-right-border-radius" value="0">
    <input type="text" data-border-radius="bottom-left-border-radius" value="0">
    <input type="text" data-border-radius="bottom-right-border-radius" value="0">

    <div class="outer-square" data-outer-square>
        <div class="inner-square" data-inner-square>
            <div data-output="top-left-border-radius"></div>
            <div data-output="top-right-border-radius"></div>
            <div data-output="bottom-left-border-radius"></div>
            <div data-output="bottom-right-border-radius"></div>
        </div>
    </div>

<script>
const innerSquare = document.querySelector("[data-inner-square]")
const outerSquare = document.querySelector("[data-outer-square]")
const inputs = document.querySelectorAll("[data-border-radius]")
const outputs = document.querySelectorAll("[data-output]")

inputs.forEach(input => {
    input.addEventListener('input', (e) => {
        const borderRadius = input.dataset.borderRadius

        if(borderRadius == 'top-left-border-radius'){
            outerSquare.style.borderTopLeftRadius = `${input.value}px`
        }else if(borderRadius == 'top-right-border-radius'){
            outerSquare.style.borderTopRightRadius = `${input.value}px`
        }else if(borderRadius == 'bottom-right-border-radius'){
            outerSquare.style.borderBottomRightRadius = `${input.value}px`
        }else outerSquare.style.borderBottomLeftRadius = `${input.value}px`
    })
    }) 
</script>
</body>
</html>

Any help will be appreciated.

Combining search and checkbox javascript filter on table

I have a search filter and checkbox filter on an html table that are both working well, but they work independently. I would like to be able to check a category, and then use the search box within that category. Right now, if I start searching, the checkbox resets and vice versa.

I think there may be two ways to do this – either update the GetElement functions to only fetch what is displayed, or to combine the two if/else statements into one. But I’m self-taught and this is all new to me so I’m having trouble writing the correct code!

function myFunction() {
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }       
  }
}
        // Select cluster
$(document).ready(function() {
  $('input[type="checkbox"]').change(function() {
    var inputValue = $(this).attr("value");
    var checked =  $(this)[0].checked;
    $("tr").each(function() {
      if($(this).find("td:eq(1)").html()!== undefined && $(this).find("td:eq(1)").html().includes( inputValue.toString())) { 
        if(checked) {
          $(this).show(); // slice by n numbers here
        } else {
          $(this).hide();
        }
      }
    });
  });
});

function checkedAll() {
console.log("All")
  var elements = this.form.getElementsByTagName('input');
console.log(elements)
  // iterate and change status
  for(var i = elements.length; i--;) {
    if(elements[i].type == 'checkbox') {
console.log(this)
      elements[i].checked = this.checked;
      $(elements[i]).trigger("change");
    }
  }
}

Looking for a javascript library to easily compare two methods

I vaguely remember the existence of a library which helps when rewriting legacy functions/methods.

Say we have a legacy function and a rewritten one:

var legacyFunction = function() { return 1; };
var reloadedFunction = function() { return 1; };

Is it possible to compare legacyFunction and reloadedFunction side-by-side, in the context where they are executed in production? Can someone point me to a library for this purpose?

  • google search for “javascript library compare functions”, also with “a/b testing”
  • asking chat gpt

I am expecting a link to a library.

Always show min and max of colorbar in a Plotly.js heatmap

In this example:

const z = Array.from({length: 50}, () => Array.from({length: 50}, () => Math.floor(Math.random() * 500 + 47.2)));
Plotly.newPlot('plot',  [{z: z, type: 'heatmap'}]);
<script src="https://cdn.plot.ly/plotly-2.26.0.min.js"></script>
<div id="plot"></div>

the colorbar doesn’t show precisely the min / max values. Here we only see 100, 200, …, 500, and we don’t see the min value which is close to 47.2, depending on the random sample.

How to display the min / max values in the colorbar, with Plotly?

Checking window.dataLayer in partytown thread

I’m trying to use partytown to run Google Analytics in a web worker. I’ve set up everything with the url proxies wherever necessary and now I want to check that it’s all working as expected.

The issue I’m facing is that I want to inspect the events that are being pushed to the dataLayer array. In my partytown configuration I’m forwarding the dataLayer.push method correctly. I would like to log the array to see its contents after doing some actions. Is there a way to do this? If I run console.log(window.dataLayer) on the main thread it’s just an empty array with the push method I’m forwarding. However, I know for a fact there is more stuff in the array because if I put the console log inside a partytown script I can see all its content. For example by doing this at the end of my body tag:

<script type="text/partytown">console.log(window.dataLayer)</script>

Does anyone know how to log this content directly in the console on demand? I tried running the console log in the web worker console, but that didn’t work because window is not defined in the web worker.

Check if image exist then refresh the page Javascript

I need a function that continuously checks if a specific image is displayed on the page or not
If it appears, refresh the page
Functions must be written in JavaScript
i write this code but it not work as i want

timer = setInterval(function() {
selector.attr('src',  'localhost/product/image1.jpg');

gaps between images on svg

I used svg.append(g) to lay out a bunch of square images one next to each other into <g>, but there seems to be these tiny little gaps (highlighted in yellow in the image below) that I can’t get rid of. How do I remove them?

async function drawBackground() {
var array = await randomArray();
for (var i=0; i<array.length; i++) {
  var positionX = paddingLeft + i % imgPerRowCount * imgWidth;
  var positionY = Math.floor(i / imgPerRowCount) * imgHeight + scrollY;
  layerBackground.append("image")
    .attr("x", positionX)
    .attr("y", positionY)
    .attr("width", imgWidth)
    .attr("height", imgHeight)
    .attr("xlink:href", imgPath[array[i]]);
}

I saw other posts about setting the square images’ parent div font-size: 0; to solve gaps between images, but since this is done on svg, this method doesn’t work.

enter image description here

Why does my script not work when my input goes past a certain point? Is this a Validation thing?

I’m making a game based on memorization of digits of pi, and when you type out the numbers and get it wrong then there are things that flash red, the correct answer replaces the wrong answer in the input box and the input clears. Everything works fine when the input is below ~ 28-30 but when the input has to start pushing numbers back to make room, the correct answer stops showing up and making it impossible to memorize more than 27 digits, and it should go up to 3,141.

This is what my JavaScript looks like, it’s also like my first time with JavaScript and I’ve had help, but it’s not the most efficient, also this isn’t all of it, only the stuff that matters. I also have the digits of pi below this but there are so many digits that it shouldn’t matter. Is it an HTML or CSS thing and I just don’t see it?

const input = document.getElementById("input-field")

input.addEventListener("beforeinput", myFunction)

const numbers = "1234567890.".split("")

const characterCounterElement = document.querySelector("charactercounter");
const typedCharactersElement = document.querySelector("#typed-characters");
const maximumCharacters = 3141;

input.addEventListener("keyup", (event) => {

  const typedCharacters = input.value.length;
  if (typedCharacters > maximumCharacters) {
    functionwin;
  }

  typedCharactersElement.textContent = typedCharacters;
});


function functionwin(event) {

}

function myFunction(event) {
  if (event.data && !numbers.includes(event.data)) {
    event.preventDefault()
  } else if (event.data) {
    const charno = input.value.length

    if (pi[charno] != event.data) {
      changeColor /*this function is defined elsewhere*/ ('#DA4F48')
      setTimeout(colorReset, 2000)
      input.disabled = true
      event.preventDefault()

      function1()

      setTimeout(somethingFunction, 2000)

    }
  }
}


function function1() {
  input.value += pi[input.value.length]
}

function somethingFunction() {
  input.disabled = false
  input.value = ''

}
<input type="text" id="input-field">

Why Canvas element draw my old function after clearReact?

I don’t know what to do. I cleared my canvas and my function isn’t redrawing on the graph, so I can’t locate the problem. I saw in debugger mode that something bad happened in the clearReact() function. Exactly when I drawNet() again. Does my program still remember my func and add it to the graph? How?

    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    canvas.width = window.innerWidth-30;
    canvas.height = window.innerHeight;
    var centerX = canvas.width / 2;
    var centerY = canvas.height / 2;
    let rangex = canvas.width/40;
    let rangey = canvas.height/20
    let number = -20;
    truthTableRPN = {
    '(' : 0,
    '+' : 1,
    '-' : 1,
    ')' : 1,
    '*' : 2,
    '/' : 2,
    '%' : 2,
    '^': 3
    }
    arrayFunction =[]
    stos =[]

    drawNet()
    drawNumericalInterval()
    drawAxes()
    ctx.translate(centerX, centerY);

    function drawAxes(){
        ctx.beginPath();
        ctx.strokeStyle = "black";
        ctx.moveTo(0, centerY);
        ctx.lineTo(canvas.width, centerY);
        ctx.moveTo(centerX, 0);
        ctx.lineTo(centerX, canvas.height);
        ctx.stroke();
        ctx.closePath()
    }
    
    function drawNumericalInterval(){
        for(i=0; i<=canvas.width; i+=rangex) {
            ctx.beginPath();
            ctx.fillText(number, i, centerY - 9)
            number++
            ctx.textAlign = "center"
            ctx.textBaseline = "middle"
            ctx.font = "10px Arial"
            ctx.strokeStyle = "black";
            ctx.moveTo(i, centerY - 5);
            ctx.lineTo(i, centerY + 5);
            ctx.stroke();
        }

        number = 10

        for(i=0; i<=canvas.height; i+=rangey) {
            ctx.beginPath();
            ctx.fillText(number, centerX - 9, i )
            number--
            ctx.textAlign = "center"
            ctx.textBaseline = "middle"
            ctx.font = "10px Arial"
            ctx.strokeStyle = "black";
            ctx.moveTo(centerX - 5, i);
            ctx.lineTo(centerX + 5, i);
            ctx.stroke();
        }
    }

    function drawNet(){
        for(i=0; i<=canvas.width; i+=rangex){
            ctx.moveTo(i, 0);
            ctx.strokeStyle = "rgba(180, 180, 180, 0.2)";
            ctx.lineTo(i, canvas.height);
            ctx.stroke();
            ctx.closePath()
        }
        for(i=0; i<=canvas.height; i+=rangey) {
            ctx.moveTo(0, i);
            ctx.strokeStyle = "rgba(180, 180, 180, 0.2)";
            ctx.lineTo(canvas.width, i);
            ctx.stroke();
            ctx.closePath()
        }
    }

    function getValue(znak){
        let returnvalue = truthTableRPN[znak] ?? -1
        return returnvalue
    }

    function createRPNUserFunction(){
        const myFunction = document.querySelector("#myFunction").value
        const check = document.querySelector(".siemka")
        myFunction.replace(/s/g, '');
        charArray = myFunction.match(/([wd]+)|[-+*/^()]/g)

        for(i=0; i< charArray.length; i++){
            console.log(stos)
            console.log(arrayFunction)

            char = charArray[i]
            if (/[a-z0-9]/.test(char)){
                arrayFunction.push(char)
            }
            else if(i == 0 && char == '-'){
                stos.push(char)
                arrayFunction.push(0)
            }
            else if(stos[stos.length-1] == '(' && char == '-'){
                stos.push(char)
                arrayFunction.push(0)
            }
            else if(char === ')'){
                while(stos[stos.length-1] !== '('){
                    arrayFunction.push(stos[stos.length-1])
                    stos.pop()
                }
                stos.pop()
            }
            else if(char == '+' || char == '-' || char == '/' || char == '*' || char == '^' || char == '%'){
                while (getValue(char) <= getValue(stos[stos.length-1])) {
                    arrayFunction.push(stos[stos.length-1])
                    stos.pop()
                }
                stos.push(char)
            }
            else stos.push(char)
        }
        for(i=0; i <= stos.length; i++){
            arrayFunction.push(stos.pop())
        }
        stos=''
        for (var i = 0; i < arrayFunction.length; i++) {
            if(arrayFunction[i] == '^') arrayFunction[i] = arrayFunction[i].replace('^', "**");
        }
        
        return arrayFunction
        
        // check.innerHTML += "pokaż stos: "+stos+'<br>'
        // check.innerHTML += "pokaż wyjście: "+arrayFunction+'<br>'
        // arrayFunction =[]
        // stos =[]
    }

    function changeValuesOfX(number, func){
            let temparrayFunction = func.slice();
            for(i=0; i < temparrayFunction.length; i++){
                if(temparrayFunction[i] == 'x') temparrayFunction[i] = number;
            }
            return temparrayFunction
    }

    function countYParameterFunction(func){
        stos = []

        for(i=0; i < func.length; i++){
            if(/[0-9]/.test(func[i])){
                stos.push(func[i])
            }
            else{
                a = stos[stos.length-1]
                stos.pop()
                b = stos[stos.length-1]
                stos.pop()
                stos.push(mathCalc(Number(b),Number(a), func[i]))
            }
        }
        return stos.pop()
    }

    function mathCalc(firstVar, secondVar, operator){
        switch(operator){
            case '**':
                return result = firstVar ** secondVar
            break;
            case '%':
                return result = firstVar % secondVar
            break;
            case '*':
                return result = firstVar * secondVar
            break;
            case '/':
                return result = firstVar / secondVar
            break;
            case '+':
                return result = firstVar + secondVar
            break;
            case '-':
                return result = firstVar - secondVar
            break;
        }
    }

    function drawFunctionGraph(arrayFunction){
        counter = 0
        let color = document.querySelector('#color').value;
        let rangex = canvas.width/40;
        let rangey = canvas.height/20
        let maxPlusX = centerX
        let maxMinusY = -centerY
        let maxMinusX = -centerX
        let maxPlusY = centerY
        for (let number = -20; number <= 20; number+=0.1) {
            array = changeValuesOfX(number, arrayFunction)
            y = (countYParameterFunction(array))
            x = number* rangex
            y *= -rangey
            console.log(x, y);

            if(counter == 0 && y>=maxMinusY && y<=maxPlusY && x>maxMinusX && x<maxPlusX){
                ctx.beginPath()
                ctx.strokeStyle = color
                ctx.moveTo(tempX, tempY);
                ctx.lineTo(x, y)
                ctx.stroke() 
                i++
                counter++
            }

            else if(counter>0) {
                ctx.strokeStyle = color
                ctx.lineTo(x, y)
                ctx.stroke()
                ctx.moveTo(x, y); 
                i++
                counter++
            }
            else{
                tempX = x
                tempY = y
                continue
            } 

            ctx.closePath()
        }
    }

    function clearReact(){
        ctx.translate(-centerX, -centerY);
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        number = -20;
        drawNet()
        drawNumericalInterval()
        drawAxes()
        ctx.translate(centerX, centerY);
    }

    function createNewGraphFunction(){
        arrayFunction = createRPNUserFunction()
        drawFunctionGraph(arrayFunction)
        arrayFunction =[]
        stos =[]
    }

Limit the Primefaces datePicker hour, minutes and seconds to given values

I am using a datePicker Primefaces element in order to allow the user to select a value for the hours, minutes and seconds. Currently, the hour has values between 0 and 24, the minutes are between 0 and 60 and same for the seconds.

I want to limit this possibility of choice to some static values, obtained from getting the length of a video posted on the page.

So, for example, if the video has 1 minute and 30 seconds, I want the hours part not to allow the user to press the arrow up or down, the minutes to be maximum 30 and the minutes 1.
I tried the below code, but it does not work – I manage to see the max length of the video when I enter the page, but if I move the arrows from the datePicker element, I can select anything.

What can I do?

The UI datePicker element:

<p:outputPanel styleClass="input-group timestamp-input">
                                <p:datePicker id="timeDatePicker"
                                              widgetVar="widgetVarOfDatePicker"
                                              value="#{traineeDashboard.newIncidentTimestamp}"
                                              timeOnly="true"
                                              showSeconds="true"
                                              appendTo="@this">
                                    <f:converter converterId="timeConverter"/>
                                </p:datePicker>

JS Code:


function setMaxTimeForDatePicker(hours, minutes, seconds) {
    var timePicker = PF('widgetVarOfDatePicker'); 
    var hoursDropdown = $('div.ui-hour-picker span:eq(1)');
    var minutesDropdown = $('div.ui-minute-picker span:eq(1)');
    var secondsDropdown = $('div.ui-second-picker span:eq(1)');

    hoursDropdown.text(hours);
    minutesDropdown.text(minutes);
    secondsDropdown.text(seconds);

    hoursDropdown.trigger('change');
    minutesDropdown.trigger('change');
    secondsDropdown.trigger('change');
}

$(function() {
    var timePicker = PF('widgetVarOfDatePicker'); // Replace with your actual widgetVar

    // Override the behaviors for incrementing and decrementing hours, minutes, and seconds
    timePicker.cfg.onHourChange = function(newHour) {
        let maxHour = 2;
        let minHour = 0;
        if (newHour < minHour || newHour > maxHour) {
            // Set the hour back to the minimum or maximum as appropriate
            this.setTime(minHour, this.currentMinute, this.currentSecond);
        }
    };

    timePicker.cfg.onMinuteChange = function(newMinute) {
        if (newMinute < minMinute || newMinute > maxMinute) {
            // Set the minute back to the minimum or maximum as appropriate
            this.setTime(this.currentHour, minMinute, this.currentSecond);
        }
    };

    timePicker.cfg.onSecondChange = function(newSecond) {
        if (newSecond < minSecond || newSecond > maxSecond) {
            // Set the second back to the minimum or maximum as appropriate
            this.setTime(this.currentHour, this.currentMinute, minSecond);
        }
    };
});

Read Arabic text in view page [closed]

When I debugged, my controller class fetched the values including the Arabic text properly
enter image description here

but after passing this data to the View using ViewData, I m getting like this
enter image description here

So, how can I get the exact Arabic text in View page? Please help

Issue collecting data with Google Analytics

this is my first time trying to integrate google analytics for my webpage. I’ve followed a recent youtube tutorial that integrates this with a react app, although it does not seem to work.

Code I used:

const TRACKING_ID = "My Tracking Code";

ReactGA.initialize(TRACKING_ID);

const App = () => {

  useEffect(() => {
  ReactGA.send({
  hitType: "pageview",
  page: window.location.pathname + window.location.search,
  title: "Home Page",
});

  }, [])

 return (

<BrowserRouter>
  <Routes>
    <Route path='/' element={<Layout />}/>
  </Routes>
</BrowserRouter>

);
 }

Does anyone see what might be wrong?

Automatically Update React Component Based on External Class Property Changes

I have an external JavaScript class (MyClass) with a property (number) that changes automatically, but I need to update a React component whenever this property changes. I cannot modify the external class (MyClass), only the react component.

Here’s a simplified example of what I’m trying to achieve:

class MyClass {
  constructor(name, number) {
    this.name = name;
    this.number = number;
    setInterval(() => this.incrementNumber(), 1000);
  }

  incrementNumber() {
    this.number += 1;
  }
}

And the React component:

import React, { useState, useEffect } from 'react';

function App() {
  const [obj, setObj] = useState(new MyClass("omri", 0));

  useEffect(() => {
    // How can I automatically update the component when obj.number changes?
  }, [obj]);

  return (
    <div>
      {obj.name} {obj.number}
    </div>
  );
}

Constraints:
Cannot modify the MyClass external class.
Need to update the React component automatically when the number property in the external class (MyClass) changes.

What are the alternative approaches or solutions to automatically update the React component when the number property in the external class changes without altering the class?

thank you!