React cannot use hashrouter

I use babel and webpack to bundle the react app.When I import the Router, the page presents white. And the log below :

Uncaught ReferenceError: exports is not defined
    at Module../node_modules/@babel/runtime/helpers/esm/extends.js (index.css:9:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:62:1)
    at Object../node_modules/history/index.js (index.ts:20:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:62:1)
    at Object../node_modules/react-router-dom/index.js (index.js:38:2)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:62:1)
    at Object../src/App.jsx (App.jsx:5:1)

and my code :

import React from "react"
import Look from "./components/Look.jsx"
import Edit from "./components/Edit.jsx"
import "./css/index.css"
import { HashRouter, Routes, Route } from "react-router-dom";

export default function App() {
    return (
        <>
            <h1 className="title">App</h1>
            <HashRouter>
                <Routes>
                    <Route path='/' element={<Edit />} />
                    <Route path='/look' element={<Look />} />
                </Routes>
            </HashRouter>
        </>
    )
}

Wheel of Fortune – Color of each Field

This is a Weel of Fortune and I would like to modify it.

Could anyone recommend me a way to define the colors for each segment?
and if I have equal names in the segment the checkbox doesn’t work at all. It sorts the segments weird after deactivating and activating the checkbox.
I hope you can help me out.

Here is the js code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
// Helpers
shuffle = function(o) {
    for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

String.prototype.hashCode = function() {
    // See http://www.cse.yorku.ca/~oz/hash.html        
    var hash = 5381;
    for (i = 0; i < this.length; i++) {
        char = this.charCodeAt(i);
        hash = ((hash << 5) + hash) + char;
        hash = hash & hash; // Convert to 32bit integer
    }
    return hash;
}

Number.prototype.mod = function(n) {
    return ((this % n) + n) % n;
}

// List of venues. These are foursquare IDs, with the idea that eventually it'll tie in 
venues = {
    "1": "1. win",
    "2": "2. cool",
    "3": "3. yea",
    "4": "4. ster",
    "5": "5. aser",
    "6": "6. Edsafox",
    "7": "7. Bsafer",
    "8": "8. Bgreter",
    "9": "9. Jarerckpot",
    "10": "10. Booreter",
    "11": "11. Boztr",
    "12": "12. Dswalay",
    "13": "13. dsafter",
    "14": "14. jrtter",
    "15": "15. ElsdgBox",
    "16": "16. Boder",
    "17": "17. Bosster",
    "18": "18. Esdfgox",
    "19": "19. Bofgder",
    "20": "20. Boongner",
    "21": "21. Elgdasx",
    "22": "22. Bodsdsr",
    "23": "23. Bosdgr",
    "24": "24. Dissdgslay",
    "25": "25. Bodsgr",
    "26": "26. Bogser",
    "27": "27. Dglay"

};

$(function() {

    var venueContainer = $('#venues ul');
    $.each(venues, function(key, item) {
        venueContainer.append(
        $(document.createElement("li")).append(
        $(document.createElement("input")).attr({
            id: 'venue-' + key,
            name: item,
            value: item,
            type: 'checkbox',
            checked: true
        }).change(function() {
            var cbox = $(this)[0];
            var segments = wheel.segments;
            var i = segments.indexOf(cbox.value);

            if (cbox.checked && i == -1) {
                segments.push(cbox.value);

            } else if (!cbox.checked && i != -1) {
                segments.splice(i, 1);
            }

            segments.sort();
            wheel.update();
        })

        ).append(
        $(document.createElement('label')).attr({
            'for': 'venue-' + key
        }).text(item)))
    });

    $('#venues ul>li').tsort("input", {
        attr: "value"
    });
});

// WHEEL!
var wheel = {

    timerHandle: 0,
    timerDelay: 33,

    angleCurrent: 0,
    angleDelta: 0,

    size: 290,

    canvasContext: null,

    colors: ['#ffff00', '#ffc700', '#ff9100', '#ff6301', '#ff0000', '#c6037e',
             '#713697', '#444ea1', '#2772b2', '#0297ba', '#008e5b', '#8ac819',
             '#ffff00', '#ffc700', '#ff9100', '#ff6301', '#ff0000', '#c6037e',
             '#713697', '#444ea1', '#2772b2', '#0297ba', '#008e5b', '#8ac819'],

    segments: [],

    seg_colors: [],
    // Cache of segments to colors
    maxSpeed: Math.PI / 16,

    upTime: 1000,
    // How long to spin up for (in ms)
    downTime: 17000,
    // How long to slow down for (in ms)
    spinStart: 0,

    frames: 0,

    centerX: 300,
    centerY: 300,

    spin: function() {

        // Start the wheel only if it's not already spinning
        if (wheel.timerHandle == 0) {
            wheel.spinStart = new Date().getTime();
            wheel.maxSpeed = Math.PI / (16 + Math.random());  // Randomly vary how hard the spin is
            wheel.frames = 0;
            wheel.sound.play();

            wheel.timerHandle = setInterval(wheel.onTimerTick, wheel.timerDelay);
        }
    },

    onTimerTick: function() {

        wheel.frames++;

        wheel.draw();

        var duration = (new Date().getTime() - wheel.spinStart);
        var progress = 0;
        var finished = false;

        if (duration < wheel.upTime) {
            progress = duration / wheel.upTime;
            wheel.angleDelta = wheel.maxSpeed * Math.sin(progress * Math.PI / 2);
        } else {
            progress = duration / wheel.downTime;
            wheel.angleDelta = wheel.maxSpeed * Math.sin(progress * Math.PI / 2 + Math.PI / 2);
            if (progress >= 1) finished = true;
        }

        wheel.angleCurrent += wheel.angleDelta;
        while (wheel.angleCurrent >= Math.PI * 2)
        // Keep the angle in a reasonable range
        wheel.angleCurrent -= Math.PI * 2;

        if (finished) {
            clearInterval(wheel.timerHandle);
            wheel.timerHandle = 0;
            wheel.angleDelta = 0;

            $("#counter").html((wheel.frames / duration * 1000) + " FPS");
        }

/*
        // Display RPM
        var rpm = (wheel.angleDelta * (1000 / wheel.timerDelay) * 60) / (Math.PI * 2);
        $("#counter").html( Math.round(rpm) + " RPM" );
         */
    },

    init: function(optionList) {
        try {
            wheel.initWheel();
            wheel.initAudio();
            wheel.initCanvas();
            wheel.draw();

            $.extend(wheel, optionList);

        } catch (exceptionData) {
            alert('Wheel is not loaded ' + exceptionData);
        }

    },

    initAudio: function() {
        var sound = document.createElement('audio');
        sound.setAttribute('src', 'wheel.mp3');
        wheel.sound = sound;
    },

    initCanvas: function() {
        var canvas = $('#wheel #canvas').get(0);

        if ($.browser.msie) {
            canvas = document.createElement('canvas');
            $(canvas).attr('width', 1200).attr('height', 600).attr('id', 'canvas').appendTo('.wheel');
            canvas = G_vmlCanvasManager.initElement(canvas);
        }

        canvas.addEventListener("click", wheel.spin, false);
        wheel.canvasContext = canvas.getContext("2d");
    },

    initWheel: function() {
        shuffle(wheel.colors);
    },

    // Called when segments have changed
    update: function() {
        // Ensure we start mid way on a item
        //var r = Math.floor(Math.random() * wheel.segments.length);
        var r = 0;
        wheel.angleCurrent = ((r + 0.5) / wheel.segments.length) * Math.PI * 2;

        var segments = wheel.segments;
        var len = segments.length;
        var colors = wheel.colors;
        var colorLen = colors.length;

        // Generate a color cache (so we have consistant coloring)
        var seg_color = new Array();
        for (var i = 0; i < len; i++)
        seg_color.push(colors[segments[i].hashCode().mod(colorLen)]);

        wheel.seg_color = seg_color;

        wheel.draw();
    },

    draw: function() {
        wheel.clear();
        wheel.drawWheel();
        wheel.drawNeedle();
    },

    clear: function() {
        var ctx = wheel.canvasContext;
        ctx.clearRect(0, 0, 1000, 800);
    },

    drawNeedle: function() {
        var ctx = wheel.canvasContext;
        var centerX = wheel.centerX;
        var centerY = wheel.centerY;
        var size = wheel.size;

        ctx.lineWidth = 1;
        ctx.strokeStyle = '#000000';
        ctx.fileStyle = '#ffffff';

        ctx.beginPath();

        ctx.moveTo(centerX + 20, centerY - size - 20);
        ctx.lineTo(centerX - 20, centerY - size - 20);
        ctx.lineTo(centerX  , centerY - size + 20);
        ctx.closePath();

        ctx.stroke();
        ctx.fill();

        // Which segment is being pointed to?
        var change = wheel.angleCurrent + (Math.PI/2);
        var i = wheel.segments.length - Math.floor((change / ( Math.PI * 2)) * wheel.segments.length) - 1;

        if(i < 0) i = i + 27;
        console.log(i);
        // Now draw the winning name
        ctx.textAlign = "left";
        ctx.textBaseline = "middle";
        ctx.fillStyle = '#ffffff';
        ctx.font = "2em Arial";
        ctx.fillText(wheel.segments[i], centerX + 120, centerY - size + 10 );
    },

    drawSegment: function(key, lastAngle, angle) {
        var ctx = wheel.canvasContext;
        var centerX = wheel.centerX;
        var centerY = wheel.centerY;
        var size = wheel.size;

        var segments = wheel.segments;
        var len = wheel.segments.length;
        var colors = wheel.seg_color;

        var value = segments[key];

        ctx.save();
        ctx.beginPath();

        // Start in the centre
        ctx.moveTo(centerX, centerY);
        ctx.arc(centerX, centerY, size, lastAngle, angle, false); // Draw a arc around the edge
        ctx.lineTo(centerX, centerY); // Now draw a line back to the centre
        // Clip anything that follows to this area
        //ctx.clip(); // It would be best to clip, but we can double performance without it
        ctx.closePath();

        ctx.fillStyle = colors[key];
        ctx.fill();
        ctx.stroke();

        // Now draw the text
        ctx.save(); // The save ensures this works on Android devices
        ctx.translate(centerX, centerY);
        ctx.rotate((lastAngle + angle) / 2);

        ctx.fillStyle = '#000000';
        ctx.fillText(value.substr(0, 20), size / 2 + 20, 0);
        ctx.restore();

        ctx.restore();
    },

    drawWheel: function() {
        var ctx = wheel.canvasContext;

        var angleCurrent = wheel.angleCurrent;
        var lastAngle = angleCurrent;

        var segments = wheel.segments;
        var len = wheel.segments.length;
        var colors = wheel.colors;
        var colorsLen = wheel.colors.length;

        var centerX = wheel.centerX;
        var centerY = wheel.centerY;
        var size = wheel.size;

        var PI2 = Math.PI * 2;

        ctx.lineWidth = 1;
        ctx.strokeStyle = '#000000';
        ctx.textBaseline = "middle";
        ctx.textAlign = "center";
        ctx.font = "1.4em Arial";

        for (var i = 1; i <= len; i++) {
            var angle = PI2 * (i / len) + angleCurrent;
            wheel.drawSegment(i - 1, lastAngle, angle);
            lastAngle = angle;
        }
        // Draw a center circle
        ctx.beginPath();
        ctx.arc(centerX, centerY, 20, 0, PI2, false);
        ctx.closePath();

        ctx.fillStyle = '#ffffff';
        ctx.strokeStyle = '#000000';
        ctx.fill();
        ctx.stroke();

        // Draw outer circle
        ctx.beginPath();
        ctx.arc(centerX, centerY, size, 0, PI2, false);
        ctx.closePath();

        ctx.lineWidth = 10;
        ctx.strokeStyle = '#000000';
        ctx.stroke();
    },
}

window.onload = function() {
    wheel.init();

    var segments = new Array();
    $.each($('#venues input:checked'), function(key, cbox) {
        segments.push(cbox.value);
    });

    wheel.segments = segments;
    wheel.update();

    // Hide the address bar (for mobile devices)!
    setTimeout(function() {
        window.scrollTo(0, 1);
    }, 0);
}

<!doctype html>
<html>
  <head>
    <meta charset='utf-8'>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wheel</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
  </head>
  
  <body style="margin: 50px; background-color:transparent; margin-left: center;">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <script src="awm.js"></script>
  <div id="venues" style="float: left; color: white; font-size: larger; text-shadow: 10ch;"><ul /></div>
  <div id="wheel" >z
  <canvas id="canvas" width="1200" height="600"></canvas></div>
  </body>
  </html>

How to make variable’s key and value merge properly in Hugo

My Hugo code:

{{ $.Scratch.Set "i" 0 }}
var chart{{$.Scratch.Get "i" }} = "xyz"

i got assigned with value 0, ideally should get

var chart0 = "xyz"

but hugo converts everything to string or int automatically and eventually becomes:

var chart 0 = "xyz"

I’ve tried following, but apparently it’s wrong:

var 'chart{{$.Scratch.Get "i" }}' = "xyz"
//output
//var 'chart0' = "xyz"

How to convert hugo value to variable key? or How to join hugo value and plaintext properly?

How can I add DOM support with JSDOM to use functions like document.getElementById() when using NodeJS [duplicate]

Ello!

I am looking to change apart of my inner html using document.getElementById("textToChange").innerHTML.

However, I keep getting this error when I attempt to run my JS file with node filename.js

TypeError: Cannot set properties of null (setting ‘innerHTML’)
at Timeout._onTimeout (C:UsersLuke.GebbinkDocumentswallboardgitJSsslCert.js:44:58)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)

I am assuming that the JSDOM global.document is not the actual webpage. How can I make it so that I can run code that refers to my index.html’s elements using JSDOM; as it will not without it. Here is my code below.

 const jsdom = require("jsdom");
    const { JSDOM } = jsdom;
    
    const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
    console.log(dom.window.document.querySelector("p").textContent); // "This Runs, so I have JSDOM Installed"

    document.getElementById("textToChange").innerHTML = 'TEST' //This does not work

Why does this script set with `dangerouslySetInnerHTML` appear to run server-side in NextJS?

I have a situation where I am rendering HTML content from a trusted database into a web page. Some of these snippets we insert into the page have script tags that will modify the DOM. I am having a hydration issue occurring due to the nature of these scripts.

The issue I am seeing can be reproduced by running npx create-next-app, opening pages/index.js and replacing it with the following code:

const script = `
<script id="feed">
var d = document.createElement('div');
d.id = "I'm inserted on the server side!";
var s = document.getElementById('feed')
s.parentNode.insertBefore(d, s)
</script>`;

export default function Home() {
  return (
    <div>
      Hello world. Here is my SSR website.
      <div dangerouslySetInnerHTML={{ __html: script }}></div>
    </div>
  );
}

When the app runs with yarn dev you will see the following error in the browser console

Warning: Prop `dangerouslySetInnerHTML` did not match. Server: "n<div id="I'm inserted on the server side!"></div><script id="feed">nvar d = document.createElement('div');nd.id = "I'm inserted on the server side!";nvar s = document.getElementById('feed')ns.parentNode.insertBefore(d, s)n</script>" Client: "n<script id="feed">nvar d = document.createElement('div');nd.id = "I'm inserted on the server side!";nvar s = document.getElementById('feed')ns.parentNode.insertBefore(d, s)n</script>"
    at div
    at div
    at Home
    at MyApp (webpack-internal:///./pages/_app.js:37:27)
    at ErrorBoundary (webpack-internal:///./node_modules/next/dist/compiled/@next/react-dev-overlay/client.js:8:20638)
    at ReactDevOverlay (webpack-internal:///./node_modules/next/dist/compiled/@next/react-dev-overlay/client.js:8:23179)
    at Container (webpack-internal:///./node_modules/next/dist/client/index.js:323:9)
    at AppContainer (webpack-internal:///./node_modules/next/dist/client/index.js:825:26)
    at Root (webpack-internal:///./node_modules/next/dist/client/index.js:949:27) 

See more info here: https://nextjs.org/docs/messages/react-hydration-error

After some more digging I discovered that building the app and running the production build, the issue is no longer reproducible.

Even more odd, in both cases (production build and dev build) if I investigate the initial HTML response from the server, the div inserted by the script is not in the HTML.

Server response in network tab of browser devtools:

<div id="__next">
  <div>
    Hello world. Here is my SSR website.
    <!-- -->
    <div>
      <script id="feed">
        var d = document.createElement("div");
        d.id = "I'm inserted on the server side!";
        var s = document.getElementById("feed");
        s.parentNode.insertBefore(d, s);
      </script>
    </div>
  </div>
</div>

This leads me to believe that this script executed and inserted the div on the dev server, except I’m not sure why I wouldn’t see it in the response above.

How could this be? Do inline script tags inserted by dangerouslySetInnerHTML execute on the server during rendering on the NextJS dev server? Or maybe it could be a bug on the NextJS dev server?

How to detect a click event on specific button in cross domain iframe?

I have an Apple podcast embed on my page wherein I need to add some code for analytics tagging based on clicks on play and pause buttons. I have achieved this for Spotify embed using their iFrame API however Apple podcasts don’t seem to have one.

As a workaround, I am trying to find a way to access the play and pause buttons inside the iFrame and trigger a click event and add the code. Because of the cross-domain policy, the following code doesn’t return anything –

this.iframeAppleWidget = this.$el.find('iframe');
console.log(this.iframeAppleWidget[0].contentWindow.document); // Empty

After doing a lot of research, I found Window.postMessage() as a suggested solution however I’m unsure of whether it can help as I’m not trying to send any message from one window to another.

Could you please point me in the right direction?

Javascript code doesnot work on safari , rails on change submit

const elements = document.querySelectorAll('.instant-submit');
 elements.forEach((element) =>{
 element.addEventListener('change', (event) => {
event.target.form.requestSubmit();
});
});

<%= form_with(url: profile_path, method: :get) do |form| %>
  <select class="form-control filter instant-submit" id="data" name="data" >
  <option <%= params[:data] == "Weekly" ? "selected" : "" %> value="Weekly" > <%= 
 link_to "Weekly",class: 'form-control'%> </option>
 <option <%= params[:data] == "Daily" ? "selected" : "" %> value="Daily"> <%= link_to 
"Daily", class: 'form-control' %></option>
</select>
<% end %>

THis is my code, but I t doesnot work on safari ? I am trying to submit form on change select. It works on chrome and other browser but not in safari. WHy ?

THis is my code,

using papa parse function to keep polling a file which is getting updated in background

I am completely new to javascript, so i am clueless on callback and other stuffs, i could manage a working setup when a file is there with data using jquery

$.get('./File.csv', function (csvString) {
            var data = Papa.parse(csvString, { header: true, dynamicTyping: true, skipEmptyLines: true }).data;
            console.log(data)

This works fine, but now my problem is i need to poll the file and perform tasks from new rows added into, so i changed this jquery into a function to use papa parse, and used setInterval to keep polling the file

This is how it looks like now.

function_A(i,a,b,c) {
            var csvString = "./File.csv"
            var data = Papa.parse(csvString, { header: true, dynamicTyping: true, skipEmptyLines: true }).data;
            console.log(data)
            console.log(data.length)
            var i = i;
            var a = a;
            var b = b;
            var c = c;
            var interval = window.setInterval(function () {
                console.log(data[i]);
                console.log("Value of i: " + i)
                var row = data[i];
                if (condition) {
                    a++;
                } else if (condition) {
                    b++;
                } else if (condition) {
                    c++;
                } else {
                    pass
                }
                i++;
                function_B(a,b,c);
                function_C(a,b,c);
                console.log("Value of i after end of iteration: " + i)
                console.log("a: " + a + " b: " + b + " c: " + c)
                if (i == data.length) {
                    console.log("I am in if loop")
                    clearInterval(interval);
                }
            }, 2000);
            return { i, a, b, c };
        }

function_B(){}
function_C(){}

var interval = window.setInterval(function () {
            var csvString = "./File.csv"
            var data = Papa.parse(csvString, { header: true, dynamicTyping: true, skipEmptyLines: true }).data;
            console.log("No Data to load" + data)
                if (data.length > 0) {
                    console.log("Starting the main function")
                    clearInterval(interval);
                    let retured_data = function_A(0, 0, 0, 0);
                    let i = retured_data.i;
                    let a = retured_data.a;
                    let b = retured_data.b;
                    let c = retured_data.c;
                    var interval_next = window.setInterval(function () {
                        i++
                        let retured_data = function_A(i, a, b, c);
                        let i = retured_data.i;
                        let a = retured_data.a;
                        let b = retured_data.b;
                        let c = retured_data.c;
                        if (data.length == 191) {
                            console.log("Complete Data Loaded")
                            clearInterval(interval_next);
                        }
                    }, 3000);
}, 2000);

I know it’s a poor code, i am not trying to be clean, just want this to work, please help. The problem is in the main function papa parse doesn’t return anything for rest of the piece to work, i tried changing code using await and promise and call back. If anyone can help me with fixing below code would appreciate

Link not routing to component

When I click on a link, it will update the URL properly. However, the component associated with that route will not appear on screen.

index.js:

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

App.js:

function App() {
  return (
    <div className="App">
      <h1>
        React Router Tester
      </h1>
      <Routes>
        <Route path="/Home" component = {Home}/>
      </Routes>

      <Link to="/Home">
      Test
      </Link>
    </div>
  );
}

export default App;

How to launch a function when an event stop?

Anyone knows how I cant check when an event stop?

Im coding a game just to learn how to use the canvas tag on HTML. To make player move, Im using switch case like this:

switch (event.code) {
case 'ArrowUp':
  // code
  break;
case 'ArrowDown':
  break;
case 'ArrowRight':
  // code
  break;
case 'ArrowLeft':
  // code
default:
  break;}

But I need to launch a function when the user stop to press the key.

Update ng-if variable from ts file

In my angularjs app written with typescript, I am trying to add an asterisk to a certain field in the html using ng-if

  <td class="abc" >                    
      <span ng-if="vm.showStar() == true && vm.Id == myItem.Id">{{myitem.myValue}}*</span>
      <span ng-if="vm.showStar() != true">{{myitem.myValue}}</span>
    </span>
  </td>

In the ts file, I have what is i guess a javascript function to which i am passing the rootscope in order to capture the event emitted from elsewhere.

function myCtrlr(

  $rootScope,

....
  $rootScope.$on('myEvent', function(event,data) {
    debugger;
    console.log(event);
 vm.showStar = true;

});

The event is captured successfuly

In the ts file, There is also an interface which contains variables. The interface and javascript function are linked using a line like this:

export default angular.module('myapp.controller.hourlyCheck', requires)
  .controller('MyCheckCtrl', myCtrlr)
  .name;

But when the event comes in it is not updating the variable showStar in the html. How can I get it to update?

How to open a modal with a form inside when any button within my table is clicked in one function

I have a modal within a div I want to pop up when any button inside my table is clicked. it will be fetching data from an API as the question and the form is for the user to answer and it will display either correct or incorrect and each button will show it’s been ‘used’ after being clicked. The table has 5 columns and 6 rows including the title row. I am trying to create an onclick function for this.

       

          <tr>
            <td><button id="21" data-category="255">500</button></td>
            <td><button id="22" data-category="190">500</button></td>
            <td><button id="23" data-category="135">500</button></td>
            <td><button id="24" data-category="145">500</button></td>
            <td><button id="25" data-category="130">500</button></td>
          </tr>
        </table>
      </div>
      <div class="board">
        <!-- categories get injected here -->
     </div>
      <!-- answers container -->
      <div class="card-modal">
        <button type="button" class="open-modal" data-open="modal1">...</button>
        <div class=card-modal-inner>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
           <h2 class="clue-text"><!-- clue gets added here --></h2>
           <form autocomplete="off">
              <input name="user-answer" type="text" />
              <button type="submit">Answer</button>
           </form>
           <div class="result">
              <p class="result_success">CORRECT</p>
              <p class="result_fail">INCORRECT</p>
              <p class="result_correct-answer">
                 The correct answer is <span class="result_correct-answer-text"><!--answer gets injected here--></span>
              </p>
           </div>
        </div>
     </div>
 </div>

Skip element and proceed to the next if not on a webpage [duplicate]

Provided below is the code that I am having a problem with. On the webpage I am loading prewritten answers for different requirements. The problem is when it comes to a requirement that doesnt exist on the webpage (i.e RDS-005) it stops and doesnt autofill for the remaining questions. How can I skip over a requirement that isnt present and move onto the next one? Thanks

*Update, I dont just need to know how to tell if an element exists on a webpage. I need to find a way to skip ones that are not present and move onto the next. Im not too familiar with child nodes. Please help… I am super stuck and have spent hours on this

function InsertAddlQuestions() {
  expandAddlOptions();

var requirementID = "REL-001";
 var question =
    "# Which ";
  AppendTBRQAInAddlOption(requirementID, question);

 requirementID = "CFN-001";
 question =
    "# Which d";
  AppendTBRQAInAddlOption(requirementID, question);

  requirementID = "CFN-002";
  question =
    "# Which advanced wor";
  AppendTBRQAInAddlOption(requirementID, question);

  requirementID = "CFN-003";
  question =
    "# Which ";
  AppendTBRQAInAddlOption(requirementID, question);

  requirementID = "CFN-004";
  question =
    "# Do you use Clo";
  AppendTBRQAInAddlOption(requirementID, question);

  requirementID = "CFN-005";
  question =
    "# How do you ";
  AppendTBRQAInAddlOption(requirementID, question);

  requirementID = "RDS-005";
  question =
    "# How do ";
  AppendTBRQAInAddlOption(requirementID, question);

  requirementID = "CFN-006";
  question =
    "# What outputs";
  AppendTBRQAInAddlOption(requirementID, question);

  requirementID = "CFN-007";
  question =
    "# What version ";
  AppendTBRQAInAddlOption(requirementID, question);
  requirementID = "CFN-008";
  question =
    "# Do you use ";
  AppendTBRQAInAddlOption(requirementID, question);

  requirementID = "CFN-009";
  question =
    "# Have you ?";
  AppendTBRQAInAddlOption(requirementID, question);
}

function AppendTBRQAInAddlOption(requirement, question) {
  console.log("Added item : " + requirement);
  var initialVal = document.getElementById(requirement).childNodes[2]
    .childNodes[0].childNodes[1].childNodes[0].childNodes[0].childNodes[0]
    .childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[2]
    .childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0]
    .value;
  if (initialVal.trim() == "") initialVal += "Q: " + question + "n" + "A:";
  else initialVal += "nQ: " + question + "n" + "A:";
  document.getElementById(
    requirement
  ).childNodes[2].childNodes[0].childNodes[1].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[2].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].value = initialVal;
}`
 

render dishes in app after passed to props react javascript JSX

Lately i have been taking this course on coursera by HKU.

The thing is, everything works fine but the damn dishdetailcomponent that is supposed that show details and comments for the damn dishes when clicked in a new page (or pseudo page)

this is example of dishes.js

export const DISHES =
[
    {
    id: 0,
    name:'Uthappizza',
    image: '/assets/images/uthappizza.png',
    category: 'mains',
    label:'Hot',
    price:'4.99',
    featured: true,
    description:'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.'                    
    },

my app.js

 import Main from './components/MainComponent';
 import { Component } from 'react';
 import './App.css';
 import {BrowserRouter} from 'react-router-dom';


class App extends Component {

render() {
      return (
        <BrowserRouter>
          <Main/>
          
        </BrowserRouter>
      );
 }
}

export default App;

my main component

import Menu from './MenuComponent';
import {DISHES} from '../shared/dishes';
import { Component } from 'react';
import Header from './HeaderComponent';
import Footer from './FooterComponent';
import {Routes, Route, Navigate} from 'react-router-dom';
import Home from './HomeComponent'
import Contact from './ContactComponent';
import { COMMENTS } from '../shared/comments';
import { PROMOTIONS } from '../shared/promotions';
import { LEADERS } from '../shared/leaders';
import DishDetail from './DishdetailComponent'
import About from './AboutComponent';


 class Main extends Component {
  constructor(props) {
   super(props);
   this.state = {
      dishes: DISHES,
      comments: COMMENTS,
      promotions: PROMOTIONS,
      leaders: LEADERS,
  
  };
}





 render() {

  const HomePage = () => {
    return(
       <Home 
          dish={this.state.dishes.filter((dish) => dish.featured)[0]}
          promotion={this.state.promotions.filter((promo) => promo.featured)[0]}
          leader={this.state.leaders.filter((leader) => leader.featured)[0]} 
       />
 );

   }


const ContactPage =()=>{
  return(
    <Contact/>
  );
}

const AboutPage =()=>{
  return(
    <About leaders={this.state.leaders}/>
  );
}

const DishWithId = ({match}) => (
  <DishDetail dish={this.state.dishes.filter((dish) => dish.id === parseInt(match.params.dishId, 10))[0]} />
);

      return (
        <div>
          <Header />
          <Routes>
            <Route path='/home' element={<HomePage/>}/>
            <Route path='/contactus' element={<Contact/>}/>
            <Route exact path='/menu' element={<Menu dishes={this.state.dishes}/>}/>
            <Route path='/menu/dishId' element={<DishWithId />} />
            <Route path='/' element={<Navigate to='/home'/>}/>
            <Route path='/aboutus' element={<AboutPage/>}/>
          </Routes>
          <Footer />
        </div>
      );
  }
}

 export default Main;

my menu component

import React/*, { Component }*/ from "react";
import {
  Card,
  CardImg,
  CardImgOverlay,
  CardTitle,
  Breadcrumb,
  BreadcrumbItem,
        } from "reactstrap";
  import {Link} from "react-router-dom";

function RenderMenuItem({dish}) {
  return(
    <Card>
    <Link to={`/menu/${dish.id}`}>
      <CardImg width="100%" src={dish.image} alt={dish.name} />
      <CardImgOverlay>
        <CardTitle> {dish.name}</CardTitle>
      </CardImgOverlay>
    </Link>
    
    </Card>
    
  );
} 

const Menu = (props) =>{
  const menu = props.dishes.map((dish) => {
    return (
      <div key={dish.id} className="col-12 col-md-5 m-1">
        <RenderMenuItem dish={dish} />  
      </div>
      
    );
  });

  return (
    <div className="container">
      <div className="row">
        <Breadcrumb>
          <BreadcrumbItem><Link to='/home'></Link></BreadcrumbItem>
          <BreadcrumbItem active>Menu<Link to='/home'></Link></BreadcrumbItem>
        </Breadcrumb>
        <div className="col-12">
          <h3>Menu</h3>
          <hr></hr>
        </div>
      </div>
      <div className="row">{menu}</div>
    </div>
  );
}











   export default Menu;

The ultimate thing is, the course is in an older version of react, but i am struggling to keep the content updated, does not seem like it would be useful learning what was used years ago.

I would really appreciate if you can point to me what am i doing wrong and how can i make it to see the dishes with their descriptions on click
enter image description here

Vue.js Directive inserted/bind overwrite eventListener click event

okay, here’s the problem.

say I have multiple dropdowns or elements on the page that all use this directive I’ve used called closable. this calls an expression passed in if the element clicked is outside of the element using the directive.

however..
the expected behaviour is that if I click an element on page ie.. another dropdown with a directive it should get that click event path compare them to the existing one and if they don’t match or aren’t contained in the elemement it should close it.

what actually happens is the click event is never registered, it just initalizes another directive and for some reason that click event is lost.

the only time the click event is registerd is if I click on something that doesn’t have the directive.

not sure why but hoping someone can help.

Vue.directive ( 'closable', {
    inserted: ( el, binding, vnode ) => {
        // assign event to the element
        el.clickOutsideEvent = function ( event ) {
            console.log ( {el, event} );
            // here we check if the click event is outside the element and it's children
            if ( !( el == event.path[0] || el.contains ( event.path[0] ) ) ) {
                // if clicked outside, call the provided method
                vnode.context[binding.expression] ( event );
            }
        };
        // register click and touch events
        document.body.addEventListener ( 'click', el.clickOutsideEvent );
        document.body.addEventListener ( 'touchstart', el.clickOutsideEvent );
    },
    unbind: function ( el ) {
        // unregister click and touch events before the element is unmounted
        document.body.removeEventListener ( 'click', el.clickOutsideEvent );
        document.body.removeEventListener ( 'touchstart', el.clickOutsideEvent );
    },
    stopProp ( event ) {
        event.stopPropagation ();
    },
} );