How to make copies of classes in javascript canvas and access their elements

I have a class called invaders which hold the properties of an image. I want to take that class, make copies of said invaders and give them a new positions which is the “this.x” and “this.y”. I was able to push the class in an array and I have a loop that runs and controls the amount of enemies I want to be displayed, but I am unable to access their position in order to change it for lets the say the second invader.

I believe my loop runs fine because when I console log the length it does say the right amount so I think they are all stacked on top of each other which makes sense as I still can’t figure out how to change the position for each.

let invaderCount = 5
const allInvaders = []
class Invaders{
    constructor(){
        this.x = 200
        this.y = 200
        this.width = 50
        this.height = 50
        const image = new Image();
        image.src = './image/invader.png'
        this.image = image
    }
    draw(){
        ctx.drawImage(this.image, this.x, this.y, this.width, this.height)
    }
    update(){
        this.draw()
    }
}
const invaders = new Invaders()
for(let i=0; i < invaderCount; i++){
    allInvaders.push(invaders)
}
console.log(allInvaders.length)
function animate(){

    requestAnimationFrame(animate)

    invaders.update()

}
animate()

Subscription class not found: Rails ActionCable

I am trying to add an instant messaging function to my Rails 7 app. I keep getting the following error:

Started GET "/cable" [WebSocket] for ::1 at 2023-04-25 03:28:15 +0100
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
Subscription class not found: "ConversationsChannel"

I have this in app/channels/conversation_channel.rb:

class ConversationsChannel < ApplicationCable::Channel
 def subscribed
    conversation = Conversation.find(params[:conversation_id])
    stream_for conversation
  end
end

My div for displaying the conversation:

<div class="well w-full md:ml-5 flex-1 h-4/5" data-channel-subscribe="conversations" data-conversation-id="<%= @conversation.id %>">
  #rest of html
</div>

Javascript:

import consumer from "/channels/consumer";

  $(function() {
    $('[data-channel-subscribe="conversations"]').each(function(index, element) {
      var $element = $(element),
          conversation_id = $element.data('conversation-id'),
          messageTemplate = $('[data-role="message-template"]');

      consumer.subscriptions.create(
        {
          channel: "ConversationsChannel",
          conversation_id: conversation_id
        },
        {
          received: function(data) {

        if (data.sender_id === gon.current_user_id) {
          var ul = document.getElementById("list");
          var li = document.createElement("li");
          li.classList.add('me');
          li.appendChild(document.createTextNode(data.body));
          ul.appendChild(li);
        } else {
          var ul = document.getElementById("list");
          var li = document.createElement("li");
          li.classList.add('him');
          li.appendChild(document.createTextNode(data.body));
          ul.appendChild(li);
        }

        document.getElementById('body').value = ''
        var objDiv = document.getElementById("messages-scroll");
        $("#messages-scroll").scrollTop($("#messages-scroll")[0].scrollHeight);

      }
    }
  );
});


});

Am I missing something obvious? I can’t figure it out so any help would be appreciated. Thanks in advance.

Android Talkback issue in latest devices

I develop a web application in the Javascript and I using Talkback for visually impaired.
But the issue is why touchstart event is not rasied in Talkback environment. Is this normal operation?
In Apple’s IOS touchstart event does raises first and click event comes.

How do I raise touchstart event in Talkback mode.

How Can I Create a Dynamic “SEO” URL with vanilla JS

I hope you could help me.
I want to change the page (“home” to “about us”) with animation. But not reload the content.
I just want an animation in the “hero banner”, but at the same time change the url (example.com to example.com/aboutUs) and obviosly change the content.

And if I will search “aboutUs Company (example)” on google, shows “about us” content with the content about “about us” in the hero without pass for “the home animation”.

Example

For Example: https://www.prevint.pt/en/seek-help/death-threats

So… I Just want to create this “dynamic route” without loading. And create an animation With Vanilla Js.
(All of things thinking in SEO)

Thank you!!!

For the main reason is SEO and this gives me a lot of problems.

Is there a better approach to this type of vanilla javascript functions?

I was doing a simple project of background themes and everything is working as expected, but the code in the javascript was very repetitive since the complete project has 9 colors.

I’d like to know if there’s a better way to do it without getting a lot of extensive code (in short, the extensive code in my point of view is a very polluted code). I want to know how much I can improve using only javascript without a js framework or js library, if not, I would also like to hear about a best practice to avoid repeating the same function several times

You can see an example of the project https://codepen.io/Leonardo-Lopes-Honda/pen/LYgWrNN

Uncaught TypeError: jQuery function is not a function

I’m having a problem with this sample code. When I try to execute someFunc(), I get the error:
Uncaught TypeError: $.twbsPagination is not a function.

<html>
<head>
<script type='text/javascript' src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="//code.jquery.com/jquery.min.js"></script>
<script src="~/Scripts/jquery.twbsPagination.js"></script>
</head>

<body>

...

<td>
    <button id="button" onclick="someFunc(); return false;">Display Pages</button>
</td>
<div id="pagination-demo"></div>

...
<script>
   function load() {
       $('#pagination-demo').twbsPagination({  // THIS WORKS.
           totalPages: 35,
           visiblePages: 7,
           onPageClick: function (event, page) {
               $('#page-content').text('Page ' + page);
           }
       });
   }
      
   function someFunc() {
      $.twbsPagination(); // THIS DOESN'T WORK.
   }
}
</script>

</body>
</html>

I’ve also tried:

function someFunc() {
   $('#pagination-demo').twbsPagination({
           totalPages: 10,
           visiblePages: 7,
           onPageClick: function (event, page) {
               $('#page-content').text('Page ' + page);
           }
       });
   }

This doesn’t work, either. I still get the above Uncaught TypeError. How do I fix this? It just doesn’t seem to work when called from the onClick event.

Why my Angular mat-table is not showing up

I am using Angular 15.2 and having following data structure defined in the component.ts file:

export interface Employee {
  Id : number,  
  FirstName:string, 
  LastName:string,  
  Email:string,
  Gender:string,    
  JobTitle:string
}
...
_the_content : Employee[] =[{
    "Id": 1,
    "FirstName": "Johannah",
    "LastName": "Kiffin"
  }, {
    "Id": 2,
    "FirstName": "Eldin",
    "LastName": "Astbery"
  }, {
    "Id": 3,
    "FirstName": "Nahum",
    "LastName": "Mounce"
  }, {
    "Id": 4,
    "FirstName": "Gallard",
    "LastName": "Standell"
  }];

Then in component.html, I have:

<div class="container">
  <table class="table table-responsive table-striped center">
    <tr>
      <th>#Id</th>
      <th>First Name</th>
      <th>Last Name</th>
    </tr>
    <tr *ngFor="let row of _the_content">
      <td>{{row.Id}}</td>
      <td>{{row.FirstName}}</td>
      <td>{{row.LastName}}</td>
    </tr>
  </table>
<div>
<div class="container">
  <table mat-table class="emp-data-table" [dataSource]="_the_content">
  
    <ng-container matColumnDef="id">
        <th mat-header-cell *matHeaderCellDef>#Id</th>
        <td mat-cell class="id-cell" *matCellDef="let row">{{row.Id}}</td>
    </ng-container>
  
    <ng-container matColumnDef="first-name">
        <th mat-header-cell *matHeaderCellDef>First Name</th>
        <td mat-cell class="first-name-cell" *matCellDef="let row">{{row.FirstName}}</td>
    </ng-container>
  
    <ng-container matColumnDef="last-name">
        <th mat-header-cell *matHeaderCellDef>Last Name</th>
        <td mat-cell class="last-name-cell" *matCellDef="let row">{{row.LastName}}</td>
    </ng-container>
    
    <tr mat-header-row *matHeaderRowDef="_displayed_columns"></tr>
    
    <tr mat-row *matRowDef="let row; columns: _displayed_columns"></tr>
    
  </table>
<div>

Also in app.module.ts, I have:

import { MatInputModule } from "@angular/material/input";
import { MatTableModule } from "@angular/material/table";
import { MatSortModule } from "@angular/material/sort";
import { MatPaginatorModule } from "@angular/material/paginator";
import { MatProgressSpinnerModule } from "@angular/material/progress-spinner"

...
imports: [
    ...
    MatInputModule,
    MatTableModule,
    MatPaginatorModule,
    MatSortModule,
    MatProgressSpinnerModule
    ...
]

Now the first table is showing up, but the second table does not.

What am I missing here?

I made sure the data are available in the html file by creating two tables referencing them, and the first table is showing while the second is not.

$ in $.ajax not defined in JavaScript

I’m using jQuery to connect HTML and Python, but the following code won’t work because $ is not defined. I researched it and found nothing that could help me that I haven’t already done.

<script
          src="https://code.jquery.com/jquery-3.6.4.min.js"
          integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
          crossorigin="anonymous"></script>
<script>
    
    function myFunction() {
    const firstname = document.getElementById('fname').value;
    const lastname = document.getElementById('lname').value;

    const dict_values = {firstname, lastname}
    const s = JSON.stringify(dict_values);
    console.log(s)
    window.alert(s)
    $.ajax({
        url:"/test",
        type:"POST",
        contentType: "application/json",
        data: JSON.stringify(s)});
}
  
</script>

I added more to the first script, but nothing changed.

How to debug chrome crash

I’m developing a chrome extension to prettify an internal website, it works well in most cases. But some guys reports a bug, when moving a selected text area with mouse operation, chrome would suddently exit, issue could be reproduced again after chrome reboot, issue would disappear after uninstallation of my extension(not so sure about this as it’s hard to reproduce).

Actually my extension would do nothing when moving text, so I have no idea how to fix it.

To root cause it, I suppose the straightforward way is to check chrome crash log. After web searching, some old post said, chrome_debug.log may help, but I could not find it anywhere in latest chrome version 112, is it depracated now?

How to debug the chrome crash issue? Thanks.

I tried to get log with following command, but didn’t observe crash in console log.

“C:Program Files (x86)GoogleChromeApplicationchrome.exe” –enable-logging=stderr –v=1 > log111.txt 2>&1

Violentmonkey Script to Redirect Page

I’m trying to write a script that saves a url and a custom message for said url, and when I visit the url, it will redirect me to a new page with the custom message and a button to proceed to the page if I want. So far this is what I have-

// Open the IndexedDB database
var request = window.indexedDB.open("myDatabase", 1);
var db;
request.onerror = function(event) {
  console.log("Error opening database.");
};
request.onsuccess = function(event) {
  db = event.target.result;

  // Retrieve the saved URLs and messages from the database
  var transaction = db.transaction(["customMessages"], "readonly");
  var objectStore = transaction.objectStore("customMessages");
  var savedData = {};
  objectStore.openCursor().onsuccess = function(event) {
    var cursor = event.target.result;
    if (cursor) {
      savedData[cursor.key] = cursor.value;
      cursor.continue();
    }
  };

  // Function to add a new custom message and URL to the database
  function addCustomMessage() {
    var url = prompt("Enter the URL to customize:");
    var message = prompt("Enter the custom message for this URL:");
    var transaction = db.transaction(["customMessages"], "readwrite");
    var objectStore = transaction.objectStore("customMessages");
    objectStore.put(message, url);
    savedData[url] = message;
  };

  // Listen for changes to the database and update saved data
  var observer = new MutationObserver(function(mutationsList, observer) {
    for (var mutation of mutationsList) {
      if (mutation.type === 'attributes' && mutation.attributeName === 'data-custom-messages') {
        // Retrieve the updated saved data from the database
        var transaction = db.transaction(["customMessages"], "readonly");
        var objectStore = transaction.objectStore("customMessages");
        savedData = {};
        objectStore.openCursor().onsuccess = function(event) {
          var cursor = event.target.result;
          if (cursor) {
            savedData[cursor.key] = cursor.value;
            cursor.continue();
          }
        };
      }
    }
  });
  observer.observe(document.body, { attributes: true, attributeFilter: ['data-custom-messages'] });

  // Loop through the saved URLs and redirect if there is a match
  function checkSavedData() {
    for (var url in savedData) {
      if (window.location.href.indexOf(url) !== -1) {
        var message = savedData[url];
        // Display the custom message with a link to the original URL
        var confirmation = confirm(message + "nnDo you want to proceed to the original URL?");
        if (!confirmation) {
          window.location.href = "about:blank";
        }
      }
    }
  }
  checkSavedData();

  // Add a button to the custom message page to load the original URL
  var customMessagePage = document.createElement("div");
  customMessagePage.innerHTML = "<h1>Custom Message</h1><p>This is a custom message for this URL.</p><button id="load-original-url">Load original URL</button>";
  customMessagePage.querySelector("#load-original-url").addEventListener("click", function() {
    window.location.href = url;
  });
  document.body.appendChild(customMessagePage);

  // Add a button to the page to add a new custom message
  var addCustomMessageButton = document.createElement("button");
  addCustomMessageButton.innerHTML = "Add Custom Message";
  addCustomMessageButton.addEventListener("click", addCustomMessage);
  document.body.appendChild(addCustomMessageButton);

  // Listen for clicks on links and check saved data before redirecting
  document.addEventListener("click", function(event) {
    if (event.target.tagName.toLowerCase() === "a") {
      var url = event.target.href;
      if (savedData[url]) {
        event.preventDefault();
        window.history.pushState({}, "", "custom-message.html");
        document.body.setAttribute("data-custom-messages", JSON.stringify(savedData));
      }
      checkSavedData();
    }
  });
};

// Create the object store in the database
request.onupgradeneeded = function(event) {
  db = event.target.result;
  var objectStore = db.createObjectStore("customMessages", { keyPath: "url" });
};

When I load any page, it doesn’t seem to display the “Add Custom Message” button, and when I load a separate script to do so, it never redirects me. How should I go about fixing this script?

Video Recording in Ionic and Capacitor Application

I am developing a mobile application using Ionic, Angular, and Capacitor. And I need a video recording feature where I can record a video or select a video from stored videos in the file system, show its preview, and post those videos to the back end.

And I am using the latest versions of Ionic, Angular, and Capacitor.

Any suggestions?

Javascript not working in Google Chrome on cell phones

Google Chrome on an iPhone and Android cell phone won’t execute javascript code in an external file. The same website works fine with Firefox and Edge. All 3 browsers work fine on my desktop computer.

What is causing this strange oddity?

The function called occurs in a form element onBlur event.

new to html, is there a way to make a search box that opens google, or something like it?

this isn’t really for what the title says, but it’s a good example of what i would like
i would like to have a text box with text you can enter, i then want that to go in a url that you could click on, or an embed

i tried this to embed an image that can change depending on user input

<body>
    <input id="testBox1" type="text" >
    <button onclick=DisplayText()">Display Text</button>
    <p>
    <img src=http://verumignis.com/bitmapgen/<div id="displayText"></div>)alt="Circle Image">
    </p>

    <script>
    function DisplayText() { 
document.getElementById("displayText").innerText = document.getElementById("testBox1").value
    }
</script>