How can I correctly guide a character through a map using if-else movement logic in p5.js?

I’m working on a detective game assignment using p5.js (as part of a “Sleuth” case study). The detective character moves through a city map based on if…else if conditions that adjust speedX and speedY.

Here’s a simplified version of my directional logic inside the draw() function:

The detective starts at (199, 10) and needs to follow a maze-like road toward the perp at (763, 696). However, in my current implementation, the character either stops moving or goes off-road at some point.

I’ve been trying to fix this by tweaking the coordinates in each condition, but something is still off — especially during transitions between horizontal and vertical movement.

How can I improve the logic or structure of my if…else if blocks to make sure the character follows the intended route without getting stuck or going off-road?

Any help or code structuring tips would be greatly appreciated!

if (det.locationY < 135 && det.locationX < 210) {
    det.speedX = 0;
    det.speedY = 1;
}
else if (det.locationY >= 135 && det.locationY < 138 && det.locationX < 702) {
    det.speedX = 1;
    det.speedY = 0;
}
else if (det.locationX >= 702 && det.locationY < 260) {
    det.speedX = 0;
    det.speedY = 1;
}
else if (det.locationY >= 260 && det.locationX > 268) {
    det.speedX = -1;
    det.speedY = 0;
}
else if (det.locationX <= 268 && det.locationY < 448) {
    det.speedX = 0;
    det.speedY = 1;
}
else if (det.locationY >= 448 && det.locationY <= 450 && det.locationX < 827) {
    det.speedX = 1;
    det.speedY = 0;
}
else if (det.locationX >= 827 && det.locationY < 670) {
    det.speedX = 0;
    det.speedY = 1;
}
else if (det.locationY >= 670 && det.locationX < 763) {
    det.speedX = 1;
    det.speedY = 0;
}
else if (det.locationX >= 763 && det.locationY < 696) {
    det.speedX = 0;
    det.speedY = 1;
}

enter code here

JavaScript/CSS Smooth “Iris” Scroll Transition: Circle Grows but Won’t Shrink on Scroll-Up

I have a one-page site with five fullscreen “Problem” cards (#problems) and a fixed “Solution time” section (#solutions).
When the user scrolls past Problem 5 a circular mask should grow from the center (radius 0 → full viewport) revealing #solutions. Scroll-down works perfectly.

Issue
When the circle reaches full size and I scroll back up, the page instantly jumps to Problem 5 and the circle snaps closed—there’s no smooth, proportional shrinking on scroll-up.

Expected

  • Scroll-down: circle grows 0 → max, revealing “Solution time”.
  • Scroll-up: circle should shrink max → 0, smoothly revealing Problem 5 again (no jump).

Reproduction

  1. Save the three files below in one folder.
  2. Open index.html.
  3. Scroll down past Problem 5 → circle grows (OK).
  4. Scroll up → circle does not shrink, jumps instead.

script.js

(() => {
  // Get the two sections: the problems you scroll past and the solutions you reveal
  const problems = document.getElementById('problems');
  const solutions = document.getElementById('solutions');
  const body = document.body;
  const html = document.documentElement;

  /* -------- Robust way to read the current vertical scroll position -------- */
  const getScrollY = () =>
    window.pageYOffset ||
    html.scrollTop ||
    body.scrollTop ||
    window.visualViewport?.offsetTop ||
    0;

  /* -------- Calculate the vertical boundaries where the clip animation starts/ends -------- */
  let viewportHeight = window.innerHeight;
  // The top position of the solutions section
  let topOfSolutions = problems.offsetTop + problems.offsetHeight;
  // When to start revealing solutions: one viewportHeight before the section
  let startReveal = topOfSolutions - viewportHeight;
  // When to be fully revealed
  let endReveal = topOfSolutions;

  let revealRatio = 0;    // Will go from 0 (hidden) to 1 (fully revealed)
  let isLocked = false;   // Are we locking the page scroll to control the reveal?

  /* Maximum radius for the circular clip: half the diagonal of the viewport */
  const maxRadius = () => Math.hypot(window.innerWidth / 2, window.innerHeight / 2);

  /* Apply the circular clip with given radius (in pixels) */
  const setRadius = (r) => {
    const clip = `circle(${r}px at 50% 50%)`;
    solutions.style.clipPath = clip;
    solutions.style.webkitClipPath = clip;
  };

  /* -------- Functions to lock/unlock the normal page scroll -------- */
  const lockScroll = (yPos) => {
    isLocked = true;
    body.style.overflow = 'hidden';
    window.scrollTo(0, yPos);
  };
  const unlockScroll = (yPos) => {
    isLocked = false;
    body.style.overflow = 'auto';
    window.scrollTo({ top: yPos, behavior: 'auto' });
  };

  /* ---------- Main scroll handler: controls the clip during scrolling ---------- */
  window.addEventListener('scroll', () => {
    if (isLocked) return; // if we're locked, ignore normal scroll events

    const currentY = getScrollY();

    if (currentY < startReveal) {
      // Above the start zone: keep circle closed
      revealRatio = 0;
      setRadius(0);
      return;
    }
    if (currentY > endReveal) {
      // Below the end zone: circle fully open
      revealRatio = 1;
      setRadius(maxRadius());
      return;
    }

    // Inside the transition zone: compute how far we are in it
    revealRatio = (currentY - startReveal) / (endReveal - startReveal);
    setRadius(revealRatio * maxRadius());

    // Lock the scroll so we can use wheel/touch to drive the reveal
    // Decide which edge to snap to if the user reverses direction
    const midpoint = (startReveal + endReveal) / 2;
    lockScroll(currentY < midpoint ? startReveal : endReveal);
  }, { passive: true });

  /* ---------- Helper to advance the reveal by a delta, then release lock if done ---------- */
  const advanceReveal = (deltaY) => {
    // convert delta scroll into a change in ratio
    revealRatio = Math.max(0, Math.min(1, revealRatio + deltaY / viewportHeight));
    setRadius(revealRatio * maxRadius());

    if (revealRatio === 1) unlockScroll(endReveal);    // fully revealed → resume normal scroll down
    if (revealRatio === 0) unlockScroll(startReveal);  // fully hidden → resume normal scroll up
  };

  /* ---------- Mouse wheel while locked: drive the reveal ---------- */
  window.addEventListener('wheel', (e) => {
    if (!isLocked) return;    // only intercept if we're in the locked state
    e.preventDefault();       // prevent the page from scrolling
    advanceReveal(e.deltaY);
  }, { passive: false });

  /* ---------- Touch drag while locked: similar to wheel ---------- */
  window.addEventListener('touchmove', (e) => {
    if (!isLocked) return;
    e.preventDefault();
    const touch = e.touches[0];
    if (touch._prevY === undefined) {
      touch._prevY = touch.clientY;
    }
    const dy = touch._prevY - touch.clientY;
    touch._prevY = touch.clientY;
    advanceReveal(dy);
  }, { passive: false });

  /* ---------- Recalculate dimensions on resize ---------- */
  window.addEventListener('resize', () => {
    viewportHeight = window.innerHeight;
    topOfSolutions = problems.offsetTop + problems.offsetHeight;
    startReveal = topOfSolutions - viewportHeight;
    endReveal = topOfSolutions;
    if (!isLocked) {
      // update current clip if not locked
      setRadius(revealRatio * maxRadius());
    }
  });
})();

index.html

<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Iris Demo</title>
  <link rel="stylesheet" href="style.css" />
</head>
<body>

  <section id="problems">
    <h1>Do you know these problems?</h1>
    <article class="card">Problem 1</article>
    <article class="card">Problem 2</article>
    <article class="card">Problem 3</article>
    <article class="card">Problem 4</article>
    <article class="card">Problem 5</article>
  </section>

  <!-- fixed layer revealed by the circle -->
  <section id="solutions">
    <h2>Solution</h2>
  </section>

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

style.css

html,body{height:100%;margin:0;font-family:sans-serif}

/* Problems */
#problems{scroll-snap-type:y mandatory;position:relative}
#problems h1{position:sticky;top:0;background:#fff;padding:1rem;text-align:center;z-index:1}
.card{height:100vh;scroll-snap-align:start;display:flex;align-items:center;justify-content:center;font-size:2rem;color:#fff}
.card:nth-child(2){background:#90caf9}
.card:nth-child(3){background:#a5d6a7}
.card:nth-child(4){background:#ce93d8}
.card:nth-child(5){background:#ffcc80}

/* Solutions (masked) */
#solutions{
  position:fixed;inset:0;
  background:#000;color:#fff;
  display:flex;align-items:center;justify-content:center;
  font-size:2rem;
  clip-path:circle(0px at 50% 50%);
  -webkit-clip-path:circle(0px at 50% 50%);
  pointer-events:none;
  z-index:50;
}

How to enable horizontal scrolling without showing scrollbar on desktop

I am trying to create an “ecommerce website” and I added product cards in a row and the cards that overflow I want to be converted into horizontal scrollable style.

I have tried using “overflow-x: scroll;” but it shows the scrollbar that looks ugly and if I make its width zero. It only works on mobile and not on desktop.

Here is the view https://baabi.netlify.app/

can anyone provide a solution to it.

.top-products {
  display: flex;
  justify-content: flex-start;
  gap: 20px;
  overflow-x: scroll;
  padding: 20px;
  position: relative;
  cursor: grab
}

It is the code of container that I tried to enable horizontal scroll but facing issue on desktop screen. It works well as I scroll easily on mobile device but when it comes to scroll on desktop. it does not work, I do not want to use javaScript if it is possible with CSS

javascript code doesn’t work, even when proen in another application [closed]

i have a javascript program that i’m working on. i’ve tested it line by line. when the program doesn’t work i know the most recently (added) line is the problem. however, when i delete that line and try to re-run the program, it fails. i can remove ALL the code from the offending function (all that’s left are the ‘{‘ and ‘}’) and it still fails. i close the browser down, erase the cache, and try to rerun it with the offending code removed. it still usually fails. i have to literally save the program to a different name and add code line-by-line like it’s a new function entirely, building from the {} line-by-line, even the code that had proven to work previously. it is beyond frustrating and exceeds my expertise. what gives?

like, this fails sometimes in the above scenario. makes absolutely no sense!!!

function getList() {
let sngMin;
let sngMax;
let sngTemp;
let strTemp;
}

String to Datetime in Jinja2

I tried {{datetime_var.strftime(‘%Y-%m-%d’)}} but this gives error:
jinja2 error

I want to make it clear: I don’t want to convert the datetime in datetime string format on the backend because I want the datetime to be displayed according to the user’s timezone on the user’s machine. So please don’t suggest doing it on the backend because backend obviously doesn’t know the tz of a user.

Example:

  • Datetime is stored in UTC timezone in database like : 2025-06-16 05:00:25 +00:00
  • Datetime is sent directly to user side exactly the same.
  • I want the datetime to be accurate as per the timezone of the machine. Like I am in India so the datetime displayed should be: 2025-06-16 10:30:25

I hope this example makes it clear what I am trying to do. It is easy with JavaScript, I just have to use new Date(datetime_var) and I am done. How to achieve the same thing in Jinja2?

SUM of column with same Title in CSR JS [duplicate]

I have js csr code run in sharepoint 2013.

| Title    | Paid     |            OutPut
| -------- | -------- |
| A        | 2        |
| B        | 100      |           A    22
| A        | 20       |           B    110
| B        | 10       |

If I enter any third value (paid) in A or B than NAN shows

| Title    | Paid     |            OutPut
| -------- | -------- |
| A        | 2        |
| B        | 100      |           A    22
| A        | 20       |           B    NAN
| B        | 10       |
| B        | 10       |

code image attach
Sum CSR

I want more than two values with same Title entered and sum answer shown.

I want more than two values with same Title entered and sum answer shown.

| Title    | Paid     |            OutPut
| -------- | -------- |
| A        | 2        |
| B        | 100      |           A    22
| A        | 20       |           B    120
| B        | 10       |
| B        | 10       |

Update Current Time Automatically And Update Database via ajax php mysql after video fully watched

Currently I am using following code to check video is fully watched or not. (Taken from This Stackoverflow Question)

  1. I want to update watchtime/playtime updated per seconds. Currently it is getting updated on clicking pause button.

  2. Many times total video duration not get captured on first page load but works when page reloaded. Specially when video is of big / large size. How to fix it ?

  3. Want to update mysql database via ajax php after watching full video only (without fast forward / moving seekbar to end)…

  4. Can we hide seekbar of video in video.js

Current Code :

<video id="video" class="video-js" controls preload="none" width="640" height="264" poster="../assets/img/poster-for-video.jpg" data-setup="{}">
<source src="<?php echo $video_url;?>" type="video/mp4"></source>


    <p class="vjs-no-js">To view this video please enable JavaScript, and consider upgrading to a web browser that <a href="https://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a></p>
 </video>

<div id="status" class="incomplete">
  <span>Play status: </span>
  <span class="status complete">COMPLETE</span>
  <span class="status incomplete">INCOMPLETE</span>
  <br />
</div>
<div>
  <span id="played">0</span> seconds out of 
  <span id="duration"></span> seconds. (only updates when the video pauses)
</div>

JS code :

<script src="js/jquery2.0.3.min.js"></script>
<link href="src/plugins/video-js/video-js.css" rel="stylesheet">
<script src="src/plugins/video-js/video.js"></script>

<script type="text/javascript" defer="defer">
 $(document).ready(function() {
   var video = document.getElementById("video")
   var timeStarted = -1
   var timePlayed = 0
   var duration = 0

 // If video metadata is laoded get duration
  if (video.readyState > 0) getDuration.call(video)
//If metadata not loaded, use event to get it
  else {
    video.addEventListener("loadedmetadata", getDuration)
 }

  // remember time user started the video
   function videoStartedPlaying() {
     timeStarted = new Date().getTime() / 1000
   }
   function videoStoppedPlaying(event) {
       // Start time less then zero means stop event was fired vidout start event
    if (timeStarted > 0) {
       var playedFor = new Date().getTime() / 1000 - timeStarted
       timeStarted = -1
       // add the new ammount of seconds played
        timePlayed += playedFor
    }
    
    document.getElementById("played").innerHTML = Math.round(timePlayed) + ""
     // Count as complete only if end of video was reached
    if (timePlayed >= duration && event.type == "ended") {
        document.getElementById("status").className = "complete"
    }
   }

   function getDuration() {
     duration = video.duration
     document.getElementById("duration").appendChild(new Text(Math.round(duration) + ""))
         console.log("Duration: ", duration)
    }

   video.addEventListener("play", videoStartedPlaying)
   video.addEventListener("playing", videoStartedPlaying)

   video.addEventListener("ended", videoStoppedPlaying)
   video.addEventListener("pause", videoStoppedPlaying)

  });
 </script>

If metadata not loaded, use event to get it – video.addEventListener(“loadedmetadata”, getDuration) is not working…..

Where can I put Ajax function to update database after video watched fully..

              var datastring = {member_uid: <?php echo $member_uid;?>, video_uid: <?php echo $video_uid;?>}, // php values set at top of this script page
              $.ajax({                      
                type: "POST",
                url: "videos-watched-ajax.php",
                data: dataString,
                cache: false,
                success: function(html){
                    alert ('database updated successfully');
                }
                }); 

Appearance tab not showing in WordPress [closed]

enter image description here

Been asked to edit some code for a friend, but when trying to locate the appearance tab to find the code files for styles and scripts I can’t seem to find them anywhere.

I have been told I have full admin permissions, but will ask and confirm.
anything I have tried so far hasn’t worked, I’m relatively new to wordpress

HTML Content of dynamically added widget to Gridstack is being rendered as plain text

I am using the latest version of Gridstack.js in my Blazor server-side app and it is nearly working as expected.

However, when I added a dynamic widget through the api to the grid the HTML content is being rendered as text.

The code to add a widget:

<button onClick="addWidget()">Add widget</button>

<script language="javascript" type="text/javascript">
    function getGrid()
    {
        return document.querySelector('.grid-stack').gridstack;
    }

    function addWidget() {
      console.log('addWidget called');
    
      var id = 'widget-' + Math.random().toString(36).substring(2, 15);

      let n = {
        id: id,
        w: Math.round(1 + 3 * Math.random()),
        h: Math.round(1 + 3 * Math.random()),
        content: '<div>test</div>',
      };

      var grid = getGrid();
      grid.addWidget(n);
    }
</script>

This is the result:

gridstack item

Why is the HTML being rendered as text? (There are no non-printable characters that might be causing the problem).

Radio button appears with black background only on chrome

i’m currently working on a custom radio input that is working as expected. The only issue I’m facing is that the background of my radio appears black, but only on Chrome. It works fine on Firefox.

className are just Tailwind classes prefixed with tw-

I tried to use inline styles and use “important” but nothing is fixing that black background.

              <input
                type='radio'
                name={name}
                value={option.value}
                disabled={disabled}
                checked={value === option.value}
                onChange={onChange}
                className={cn(
                  'tw-mt-0.5 tw-cursor-pointer',
                  'tw-border tw-border-gray-300 tw-rounded-full',
                  'tw-accent-prim-500',
                  disabled ? 'tw-cursor-not-allowed tw-bg-gray-200' : '',
                )}
                {...inputProps}
              />

Here is a link to a screenshot :
https://i.ibb.co/sSMmP0v/Screenshot-from-2025-06-18-15-08-46.png

Thanks

How do I consolidate multiple javascript files and associated WordPress code snippets?

I have several Javascript files e.g. TITLE.js with this format and they all work fine:

jQuery( document ).on( 'click', '.click-TITLE-link', function(event) {
    event.preventDefault();
    var post_id = jQuery(this).data('id');
    jQuery.ajax({
        url : TITLElink.ajax_url,
        type : 'post',
        data : {
            action : 'click_TITLE_process',
            nonce : TITLElink.ajax_nonce,
            post_id : post_id
        },
        success : function( response ) {
            if (response) {
                  // DO SOMETHING
                }      
        }
    });
})

Each javascript file is associated with a code snippets that look like this:

<?php

add_action( 'wp_enqueue_scripts', 'ajax_TITLE_link_enqueue_scripts' );
function ajax_TITLE_link_enqueue_scripts() {
 
    wp_enqueue_script( 'TITLE-link', get_theme_file_uri( '/js/TITLE.js' ), array('jquery'), '1.0', true );
     
    wp_localize_script( 'TITLE-link', 'TITLElink', array(
        'ajax_url' => admin_url( 'admin-ajax.php' ),
        'ajax_nonce' => wp_create_nonce( 'link_TITLE_accept_' . admin_url( 'admin-ajax.php' ) ),
    ));
 
}
 
// action to execute AJAX call
add_action( 'wp_ajax_nopriv_click_TITLE_process', 'click_TITLE_process' );
add_action( 'wp_ajax_click_TITLE_process', 'click_TITLE_process' );
 
function click_TITLE_process() {
 
    if ( defined( 'DOING_AJAX' ) && DOING_AJAX && wp_verify_nonce( $_POST['nonce'], 'link_click_TITLE_' . admin_url( 'admin-ajax.php' ) ) ) {
      
        // Do something here
     
      
        // redirect back to the page
        echo "Refreshing";
    } else {
        die( 'Security check failed' );
    }
}

It seems cumbersome and not good practice to have a separate javascript file for each function, but before I give consolidation a go, I’m worried that the NONCE part won’t work?

Any help much appreciated. TIA.

Can we nest tags inside using Shadow DOM or iframe tricks?

Normally, the <html> and <body> tags define the root structure of an HTML document and are not allowed to appear inside other tags like <div>.

But I’m wondering:

Is it technically possible to “nest” an entire HTML structure — including its own <html>, <head>, and <body> — inside a <div> on the parent page?

Would it work via tricks like:

Shadow DOM (attachShadow({ mode: 'open' }))

Embedding with <iframe>

Using templates or script tags?

If yes, how does the browser interpret and render that structure?
If not, what are the specific limitations that prevent it?

Goal:
I’m exploring whether we can embed full HTML documents as modular components inside a larger HTML page — not just with iframes, but also with more modern component techniques (e.g., Web Components).

Confusion about usestate REACT JS

  import { useState } from 'react';
  import getWeatherData from './weatherApi/weather';

  interface SearchBarProps {
    text: string;
  }

  function SearchBar({text}: SearchBarProps) {

    const [city, setCity] = useState('');

    const searchClick = () => {
    const input = document.querySelector('input');
    setCity((input as HTMLInputElement).value.trim());
    getWeatherData(city);

  }
    const [x, setX] = useState(1);

  return (
    <>
      <h1 onClick={() => setX(x+1)}>Hello {text} and {x} </h1>
      <input type="text" />
      <button onClick={searchClick}>Search</button>
    </>
  );
  }

  export default SearchBar;

basically when i press the button its supposed to log out the text in it but it logs out the previous text and i am even changing the state before i log the value

where am i mistaken

How can I use a React 18 support repo inside a React 19 app without version conflicts?

I have two React repositories:

Main app – recently upgraded to React 19

Builder (support repo) – still on React 18

I upgraded my Main repo to React 19, and I’m linking my Builder repo like this in package.json:
"@myComp/builder": "git+ssh://[email protected]/myComp/builder.git#semver:0.1.18"
The builder repo has both react and react-dom listed as peerDependencies and devDependencies (not direct dependencies). However, when I connect the Builder to Main, I get the following error:
TypeError: Cannot read properties of undefined (reading 'ReactCurrentOwner')

I tried to upgrade my Builder repo & half way there, but it uses a critical library called @projectstorm/react-diagrams, which does not support React 19 yet. This library is core to my app and I cannot refactor or replace it right now due to time constraints.

Is there any safe workaround where I can:

  • Keep my Builder repo on React 18 (along with its dependencies)
  • Still use it inside my React 19 Main app
  • Avoid breaking the app due to React version mismatches

Any guidance or suggestions on safe patterns or temporary workarounds would be appreciated.