Adding Javascript to a WordPress page

It seems my code is not running when I add it to my WordPress site. It’s running just fine in VSCode. Other functions are working in the WordPress site, i.e. alert functions are responding. My styles are responding as well so I know the problem is not with enqueueing scripts in functions.php.

Perhaps my JS code is not being called in time to link with the HTML files its supposed to? I don’t know.

This is a snippet of what part of my JS code looks like. How can I change this? Or what am I supposed to wrap it in to make it work?

///nav bar size response
$('.navbar-toggle').click(function() {
  $('.navbar-nav').toggle();
});

$(document).ready(function() {
  $(".sub-btn").click(function() {
    $(this).next(".sub-menu").slideToggle();
  })
 
  $(".other-btn").click(function() {
    $(this).next(".other-menu").slideToggle();
  })
})

//button toggle
var menu = document.querySelector(".menu")
var menuBtn = document.querySelector(".menu-btn")
var closeBtn = document.querySelector(".close-btn")

menuBtn.addEventListener("click", () => {
  menu.classList.add("active");
});

closeBtn.addEventListener("click", () => {
  menu.classList.remove("active");
});

//header scroll
window.addEventListener("scroll", function() {
  var header = this.document.querySelector("header");
  header.classList.toggle("sticky", window.scrollY > 0);
});

How can I fix the error ‘webpack_require__.g.addEventListener is not a function’ in Tesseract.js with Electron and webpack?

I’m trying to build an Electron/Webpack app that uses Tesseract.js for OCR, but when I call Tesseract.createWorker, I get this error message:

A JavaScript error occured in the main process.
Uncaught Exception: TypeError: __webpack_require__.g.addEventListener is not a function...

This is the code that I’m trying to use to create the Tesseract worker:

const worker = await Tesseract.createWorker({
    workerPath: new URL('../node_modules/tesseract.js/dist/worker.min.js', import.meta.url),
    logger: m => console.log(m)
});

This project is based on the webpack-typescript Electron Forge quickstart.

I have tried changing the URL to workerPath to point directly to the tesseract.js worker script with an absolute path, but I got the same error.

Using Control statements in EJS but could not find close tag for<% [closed]

I am accessing worklist array and want to print by using for loop but when I used <% %> for control statements in EJS it showing error: Could not find matching close tag for “<%”.

code:

<div class="box">        
  <% for(var i=0;i<<%= worklist %>.length; i++){ %>
    <p><%= worklist %>[i]</p>
  <% } %>
</div>

enter image description here

please tell me what mistakes I had done & other solution.

How to run an application from git

Good afternoon, I don’t know anything about programming, but I want to run this https://github.com/otuskotlin/ok-202105-finrec-ib or https://github.com/rafaelperozin/salim application with git but it doesn’t work, I tried using android studio.

I watched videos on YouTube but it did not help. Can someone explain in detail what needs to be done to make it work and does it work at all? I will be very grateful.

Two Bootstrap carousel’s on one page conflicting [closed]

My site is using Bootstrap and I have two carousels on one page, with tabs to navigate between each slide. They seem to be conflicting with each-other, mainly around the ‘active’ class part, a different slide would show and a different tab would be highlighted.

Below is code for the first carousel, it has an ID of ‘myCarousel’

<script> $(document).ready(function(){
  var clickEvent = false;
  $("#myCarousel").on("click", ".nav a", function(){
   clickEvent = true;
   $(this).parent().siblings().removeClass("active");
   $(this).parent().addClass("active");  
  }).on("slid.bs.carousel", function(e){
   if(!clickEvent){
    itemIndex = $(e.relatedTarget).index();
    targetNavItem = $(".nav li[data-slide-to='" + itemIndex + "']");
    $(".nav li").not(targetNavItem).removeClass("active");
    targetNavItem.addClass("active");
   }
   clickEvent = false;
  });
 });</script>

This is the code for the other carousel, it has an ID for ‘case-studies’

<script> $(document).ready(function(){
  var clickEvent = false;
  $("#case-studies").on("click", ".nav a", function(){
   clickEvent = true;
   $(this).parent().siblings().removeClass("active");
   $(this).parent().addClass("active");  
  }).on("slid.bs.carousel", function(e){
   if(!clickEvent){
    itemIndex = $(e.relatedTarget).index();
    targetNavItem = $(".nav li[data-slide-to='" + itemIndex + "']");
    $(".nav li").not(targetNavItem).removeClass("active");
    targetNavItem.addClass("active");
   }
   clickEvent = false;
  });
 });</script>

ASP.NET Core MVC nullable model is never null on ajax request

I have the following action method:

    [HttpGet]
    public async Task<IActionResult> GetFilterPartialAsync(FilterViewModel? vm = null)
    {
        if (vm != null) return PartialView("_FilterPartial", vm);
        else return PartialView("_FilterPartial");
    }

If I use it from another action method like this: return await GetFilterPartialAsync(vm), the if (vm != null) condition is true. In case of return await GetFilterPartialAsync(), the if (vm != null) condition is false, since there are no arguments passed. BUT if I call the same GetFilterPartialAsync action method from ajax, the if (vm != null) condition is ALWAYS true, even though I haven’t passed any arguments in that call. Ajax:

$('#filterButton').click(function () {
    $('#filterModal .modal-dialog').load('/Home/GetFilterPartial'); //here calling the GetFilterPartial, no args
    $('#filterModal').modal('show');
});

As you can see in the pic I took after ajax request, the if (vm != null) condition is true, and the view model contains default (null/0) values, which leads to the form displaying already with error messages.

enter image description here

What leads to this unexpected behavior?

Any help is greatly appreciated!!!

How to change the list of points to be generated automatically?

How to change the list of points to be generated automatically?

I want to have access to a map on a website with an automatically generated list of points depending on which towns the user selects.

var map_459983c9521af07ce47320ce3c2214fe = L.map(
  "map_459983c9521af07ce47320ce3c2214fe", {
    center: [52.40541, 16.93126],
    crs: L.CRS.EPSG3857,
    zoom: 12,
    zoomControl: true,
    preferCanvas: false,
  }
);
var marker_ae76a19f7fb53b7a60dc703d21711c33 = L.marker(
  [52.40541, 16.93126], {
    "color": "green",
    "fillColor": "green"
  }
).addTo(map_459983c9521af07ce47320ce3c2214fe);
var marker_34e05070c9ccfcb27e56a42b7858742d = L.marker(
  [52.7294, 15.24038], {
    "color": "red",
    "fillColor": "red"
  }
).addTo(map_459983c9521af07ce47320ce3c2214fe);
var poly_line_47526c6e001992597f7909d2b9bed3d2 = L.polyline(
  [
    [52.40541, 16.93126], ..., [52.7294, 15.24038]
  ], {
    "bubblingMouseEvents": true,
    "color": "blue",
    "dashArray": null,
    "dashOffset": null,
    "fill": false,
    "fillColor": "blue",
    "fillOpacity": 0.2,
    "fillRule": "evenodd",
    "lineCap": "round",
    "lineJoin": "round",
    "noClip": false,
    "opacity": 1,
    "smoothFactor": 1.0,
    "stroke": true,
    "weight": 2.5
  }
).addTo(map_459983c9521af07ce47320ce3c2214fe);

Not able to retrieve array from object in TypeScript

Using Plotly.js in my React application, I wish to retrieve the “range” array from the layout object. This is what my code looks like:

 useEffect(() => {
        if (chartData) {
            
            console.log(chartData.layout.yaxis);
            console.log(chartData.layout.yaxis.range);

            console.log(JSON.stringify(chartData.layout.yaxis));
            
        }
    }, [chartData])

Output from console.log(chartData.layout.yaxis):

{
anchor: "x"
autorange: true
domain: (2) [0, 1]
range: (2) [-1611.7268768451163, 15422.563518243458]
title: {text: 'This is a sample text'}
type: "linear"
}

Output from console.log(chartData.layout.yaxis.range):

undefined

Output from console.log(JSON.stringify(chartData.layout.yaxis)):

{"anchor":"x","domain":[0,1],"title":{"text":"This is a sample text"}}

What I can’t get my head around is the range is clearly present as an array in the first console.log but comes out as undefined with I try to access it directly in the second console.log.

What is the explanation behind this behavior and how do I retrieve the “range” array, that clearly is there?

Why does a for loop in JavaScript catch me only the first index

I am trying to check if the username field and the password field match the fields from this api and whenever username is equal to admin and password is equal to Manastir1600- I see the message in console: “Sucsess!”

When I try to enter username admin and password: value2 I see the message in console: “Invalid username or password!”

My HTML form is:

<div class="container">
          <label for="uname"><b>Username</b></label>
          <input type="text" placeholder="Enter Username" name="uname" id="uname" required>
      
          <label for="psw"><b>Password</b></label>
          <input type="password" placeholder="Enter Password" name="psw" id="psw" required>
      
          <button type="submit" onclick="login()">Login</button>
          <label>
            <input type="checkbox" checked="checked" name="remember"> Remember me
          </label>
        </div>

My JS file is:

async function login() {
   //Get value from username and password
   const username = document.getElementById('uname');
   const password = document.getElementById('psw');
   //Fetching data
   const response = await fetch("http://194.141.118.43:3030/users");
   const jsonData = await response.json();

   //Check for database username and database
   for (const item of jsonData.users) {
      if (username.value == "" || password.value == ""){
         return alert("Username or password cannot be empty!");
      }
      if (username.value == item.user && password.value == item.password) {
          return console.log("Sucsess!")
         }else{
           return alert("Invalid username or password!");
         }
     }
 }

I want to make it so that when a person types something in the username and password fields, they are compared to the fields from the api server.

How to create a Progress Bar in NextJS’s App Directory?

I have developed a large web application with NextJS 13, the first version was using the Pages Router.

After completing almost the entire website, I managed to migrate to the App Directory.

This migration was not essentially to upgrade for some new routing features, but I wanted to change my SASS’s Large compiled file imported in the _app.tsx for better website loading time.

Since the loading was quite a big issue for this project, I started using MUI with the styling of the each component, simply a CSS-in-JS solution.

But the problem I found with the new App Directory, is the router events, I had a progress bar indicator from the next-n-progress package, but now it doesn’t work, the user clicks on a link and the app takes some small time to load the next page.

The problem is not an issue for SSR pages since I have put a loading.tsx file in the root of each page, but it persists for pages with client-side configuration.

Like the Home Page, Sign-in & Sign-up, etc.

I tried another package for the Progress Bar that supports the new app directory, but it is not showing up at all.

This is the component responsible for the Layout:
GitHub File Link

Is there any way to create a new progress bar with this new NextJS 13 Update?

PHP not add file extension

I tested this on my test server without any problems, but as i moved to production server. It doesn’t add the file extension at the end. Saved file looks like this now “123.” and not “123.jpg” or “123.png”.

For more understanding, here is my code


<?php if(!defined('IN_SYS')) header("location:$local_server/?action=profile"); ?>
<title>Profile - iBancho</title>
<script src='https://recaptcha.net/recaptcha/api.js' async defer></script>
<link rel="stylesheet" href="./styles/cropper.css">
<script src="./scripts/jquery-3.2.1.min.js"></script>
<script src="./scripts/cropper.js"></script>
<script src="./scripts/main.js"></script>
<h1>Profile</h1>
<?php
$file_name = $login_user_id;
if (isset($_GET['type'])) {
    $type = $_GET['type'];
    if ($type == "post-avatar") {
        $crop_data = $_POST['crop_data'];
        if ($crop_data == "") {
            header("location:?action=profile&stat=3");
        } else if (strlen($crop_data) > 2097152) {
            header("location:?action=profile&stat=2");
        } else {
            $crop_data_arr = explode(',', $crop_data);
            $file_extension = pathinfo($_FILES['file_avatar']['name'], PATHINFO_EXTENSION); // Get the original file extension

            // Delete existing files
            $existing_files = glob("./avatar/$file_name.*");
            foreach ($existing_files as $file) {
                if (is_file($file)) {
                    unlink($file);
                }
            }
            if (file_put_contents("./avatar/$file_name.$file_extension", base64_decode($crop_data_arr[1]))) {
                header("location:?action=profile&stat=1");
            } else {
                header("location:?action=profile&stat=4");
            }
        }
    }
} else if (isset($_GET['stat'])) {
    $stat = $_GET['stat'];
    if ($stat == 0) echo "";
    else if ($stat == 1) echo "<div class='alert-success'>Upload success.</div>";
    else if ($stat == 2) echo "<div class='alert-error'>File is too large.</div>";
    else if ($stat == 3) echo "<div class='alert-error'>Please save the crop image first.</div>";
    else if ($stat == 4) echo "<div class='alert-error'>Upload failed.</div>";
}
?>
<h3>Upload Avatar</h3>
<form id="avatar_form" action="?action=profile&type=post-avatar" method="post">
    <div id="avatar_preview">
        <img class="user_avatar_medium" id="avatar-preview-1" src="<?php
        $avatar_file_png = "./avatar/" . $login_user_id . ".png";
        $avatar_file_jpg = "./avatar/" . $login_user_id . ".jpg";
        if (file_exists($avatar_file_png)) {
            echo $avatar_file_png . "?s=200&id=" . $login_user_id . "&t=$time";
        } elseif (file_exists($avatar_file_jpg)) {
            echo $avatar_file_jpg . "?s=200&id=" . $login_user_id . "&t=$time";
        } else {
            echo "./avatar/0.png";
        }
        ?>">
    </div>
    <button type="button" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect" style="margin-right: 8px" onclick="$('#file-select-avatar').click();" id="file-select-avatar-button">Select file...</button>
    <span id="file-select-avatar-name">Please select a file</span>
    <div>
    <p style="margin-top: 45px; font-weight: bold;"><a style="color: #ea0000">*</a><a style="color: #000000" >Clear the game's cache for the new uploaded avatar to show up.</a></p>
    </div>

    <input type="file" name="file_avatar" style="display: none;" id="file-select-avatar" />
    <br><br>
    <script>
    var file_select_avatar = document.querySelector('#file-select-avatar');
    file_select_avatar.addEventListener('change', function() {
        file_select_avatar_path = $(this).val();
        file_select_avatar_path = file_select_avatar_path.replace(/C:\fakepath\/, "");
        if (file_select_avatar_path != "") {
            $('#file-select-avatar-name')[0].innerHTML=file_select_avatar_path;
            $('#file-select-avatar-upload').removeAttr("disabled");
            $('#avatar_preview').css({"display":"none"});
            // Cropper
            $('#cropper').css({"height":"auto"});
            $('.docs-buttons').css({"display":"block"});
        } else {
            $('#file-select-avatar-name')[0].innerHTML='Please select a file';
            $('#file-select-avatar-upload').attr({"disabled":"disabled"});
            $('#avatar_preview').css({"display":"block"});
            $('#cropper').css({"height":"0"});
            $('.docs-buttons').css({"display":"none"});
        }
    });
    </script>
    <div id="cropper" style="height:0;overflow:auto;position:relative;">
        <div class="img-container">
            <img id="image" src="<?php echo "./avatar/?s=200&id=$file_name&t=$time"; ?>" alt="Picture" class="cropper-hidden">
        </div>
        <div class="docs-preview clearfix" style="display: inline-block">
            <div class="img-preview preview-lg" style="width: 128px; height: 128px;"></div>
            <div class="img-preview preview-md" style="width: 64px; height: 64px;"></div>
            <div class="img-preview preview-sm" style="width: 32px; height: 32px;"></div>
        </div>
        <style>
        .docs-buttons-style {
            position: fixed;
            height: 92px;
            width: 100px;
            right: 32px;
            bottom: 32px;
            border-radius: 16px;
            display: none;
            background: white;
            box-shadow: 0 4px 5px 0 rgba(0,0,0,.14), 0 1px 10px 0 rgba(0,0,0,.12), 0 2px 4px -1px rgba(0,0,0,.2);
        }
        .docs-buttons-style>* {
            position: absolute;
            left: 0;
            top: 0;
            border: none;
            background: rgba(0,0,0,0);
        }
        </style>
        <div class="docs-buttons docs-buttons-style">
            <button type="button" data-method="setDragMode" data-option="move" title="拖拽" id="move" style="top:32px;left:32px;"><i class='material-icons'>open_with</i></button>
            <button type="button" data-method="setDragMode" data-option="crop" title="裁剪" id="crop" style="top:32px;left:32px;display:none"><i class='material-icons'>crop</i></button>
            <script>
            var move = document.querySelector('#move');
            var crop = document.querySelector('#crop');
            move.addEventListener('click', function() {
                move.style.display="none";
                crop.style.display="block";
            });
            crop.addEventListener('click', function() {
                crop.style.display="none";
                move.style.display="block";
            });
            </script>
            
            <button type="button" data-method="zoom" data-option="0.1" title="放大" style="top:0;left:0;"><i class='material-icons'>zoom_in</i></button>
            <button type="button" data-method="zoom" data-option="-0.1" title="缩小" style="top:0;left:64px;"><i class='material-icons'>zoom_out</i></button>

            <button type="button" data-method="move" data-option="10" data-second-option="0" title="左移" style="top:32px;left:0;"><i class='material-icons'>arrow_left</i></button>
            <button type="button" data-method="move" data-option="-10" data-second-option="0" title="右移" style="top:32px;left:64px;"><i class='material-icons'>arrow_right</i></button>
            <button type="button" data-method="move" data-option="0" data-second-option="10" title="上移" style="top:0;left:32px;"><i class='material-icons'>arrow_drop_up</i></button>
            <button type="button" data-method="move" data-option="0" data-second-option="-10" title="下移" style="top:64px;left:32px;"><i class='material-icons'>arrow_drop_down</i></button>

            <button type="button" data-method="rotate" data-option="-45" title="左转" style="top:64px;left:0"><i class='material-icons'>rotate_left</i></button>
            <button type="button" data-method="getCroppedCanvas" data-option="{ &quot;maxWidth&quot;: 4096, &quot;maxHeight&quot;: 4096 }" style="top:64px;left:64px;background-color: rgb(63,81,181);border-radius: 18px 0 18px;color: white;"><i class='material-icons'>done</i></button>
            <input type="hidden" name="crop_data" id="crop_data" value="" />
        </div>
        <p style="margin-top: 0;">You need to save the cropped image first before uploading it.</p>
        <input type="submit" name="submit" value="Upload">
    </div>
</form>

Not sure what cause this to fix it. It was working on a test server.

evenNums.push is not a function [closed]

Why does this give me an error “evenNums.push is not a function”. I’m so confused. I think I’m missing something.

    function divideArray(numbers= []){
    
    let evenNums = []
    let oddNums = []
    let i
    for (i = 0; i < numbers.length; i++){
        if (numbers[i] % 2 == 0){
            evenNums.push(numbers[i])

Reading Json object and create array of object in node.js

I have a backend endpoint which listen to the request and gives a JSON object
which is as below

{
    "id": "f4c0be70-7329-4f7e-8e57-dfaf598e3735",
    "created": "2023-05-25T06:32:56.633Z",
    "completed": "2023-05-25T06:33:20.698Z",
    "status": "COMPLETE",
    "type": "instruct_basics",
    "configuration": "resume",
    "environment": "development",
    "page_count": 2,
    "webhook": {
        "payload": "1684903244279x419306702443118600",
        "url": "https://some.bubbleapps.io/version-test/api/2.2/wf/some_webhook/"
    },
    "parsed_document": {
        "work_experience": {
            "columns": [
                {
                    "id": "company_name",
                    "values": [
                        {
                            "value": "facebook",
                            "type": "string"
                        },
                        {
                            "value": "google",
                            "type": "string"
                        },
                        {
                            "value": "Tesla",
                            "type": "string"
                        }
                    ]
                },
                {
                    "id": "start_date",
                    "values": [
                        {
                            "value": "August '16",
                            "type": "string"
                        },
                        {
                            "value": "July '14",
                            "type": "string"
                        },
                        {
                            "value": "January '14",
                            "type": "string"
                        }
                    ]
                },
                {
                    "id": "end_date",
                    "values": [
                        {
                            "value": "Present",
                            "type": "string"
                        },
                        {
                            "value": "June '16",
                            "type": "string"
                        },
                        {
                            "value": "June '14",
                            "type": "string"
                        }
                    ]
                },
                {
                    "id": "job_title",
                    "values": [
                        {
                            "value": "Software Engineering Intern",
                            "type": "string"
                        },
                        {
                            "value": "Developer Community Manager",
                            "type": "string"
                        },
                        {
                            "value": "Experience Design & Development Intern",
                            "type": "string"
                        }
                    ]
                },
                {
                    "id": "summary_of_responsibilities",
                    "values": [
                        {
                            "value": "Building a monitoring dashboard for datacenter, host, and application visualization; Building a library of reusable Angular 2 components",
                            "type": "string"
                        },
                        {
                            "value": "Created the developer program; Assisted the design, spec'ing, and testing of the WebRTC solution, RTCP Monitoring, and SMS API; Designed and developed the developer portal; Creation and growth of a developer community",
                            "type": "string"
                        },
                        {
                            "value": "Development of internal modes of communications; Working with the API team to develop a Developer Evangelism plan; Development of the developer documentation platform",
                            "type": "string"
                        }
                    ]
                }
            ]
        },
        "programming_languages": {
            "columns": [
                {
                    "id": "skill",
                    "values": [
                        {
                            "value": "HTML5",
                            "type": "string"
                        },
                        {
                            "value": "CSS/Sass",
                            "type": "string"
                        },
                        {
                            "value": "Angular 2",
                            "type": "string"
                        },
                        {
                            "value": "Typescript",
                            "type": "string"
                        },
                        {
                            "value": "Jasmin",
                            "type": "string"
                        },
                        {
                            "value": "NodeJS",
                            "type": "string"
                        },
                        {
                            "value": "Express",
                            "type": "string"
                        },
                        {
                            "value": "MongoDB",
                            "type": "string"
                        },
                        {
                            "value": "Git",
                            "type": "string"
                        },
                        {
                            "value": "REST API Design",
                            "type": "string"
                        },
                        {
                            "value": "Docker",
                            "type": "string"
                        },
                        {
                            "value": "Vagrant",
                            "type": "string"
                        },
                        {
                            "value": "IBM Bluemix",
                            "type": "string"
                        }
                    ]
                }
            ]
        },
        "email": null
    },
    "validations": [],
    "validation_summary": {
        "fields": 3,
        "fields_present": 2,
        "errors": 0,
        "warnings": 0,
        "skipped": 0
    },
    "classification_summary": [
        {
            "configuration": "resume",
            "score": {
                "value": 2,
                "fields_present": 2,
                "penalties": 0
            }
        }
    ],
    "errors": [],
   
    
    "payload": "1681234544279x123456702443118600"
}

then i want to run a node.js script to go through this JSON object and iterate through
Parsed_document_experience columns

I want to iterate through column and generate an array of object like below

Job Title: Global Marketing Manager
Company: blu Advertising
Start Date: October 2017
End Date: Present
Description: Enhanced open rate for online customer campaigns by 32%, developed four additional market territories in the Mid-West, established effective working relationships with sales managers and agency teams

Job Title: Marketing Manager
Company: Gree Advertising
Start Date: December 2013
End Date: September 2017
Description: Executed a Facebook-based marketing program which resulted in a 28% increase of in leads, 30% new subscribers to weekly blog

Job Title: Assistant Marketing Manager
Company: Online Shopping
Start Date: September 2010
End Date: September 2013
Description: Assisted senior manager in developing annual marketing plans and implementing marketing strategies, project management of marketing initiatives, created marketing strategies

unfortunately i have 0 knowledge of Node.js so asking help