Re-enter fullscreen mode after a JavaScript alert call

I have this web page that is already in fullscreen mode. Now, when testing with Google Chrome, if I make a call to the alert function, the page would quit fullscreen mode.

While I understand that this might be standard behavior, I would still like to make the page re-enter fullscreen mode after quitting it. I now have this function:

function enterFullScreen() {
    let element = document.documentElement;
    if (element.requestFullscreen) {
        element.requestFullscreen();
    }
    else if (element["mozRequestFullScreen"]) {
        element["mozRequestFullScreen"]();
    }
    else if (element["webkitRequestFullscreen"]) {
        element["webkitRequestFullscreen"]();
    }
    else if (element["msRequestFullscreen"]) {
        element["msRequestFullscreen"]();
    }
}

It works fine when I run it directly in the console, but when I put it after the alert call, believing it would make the page re-enter fullscreen mode, it ceases to work:

elem.onclick = function () {
    alert("something");
    enterFullScreen(); // Nothing happens what-so-ever. No errors either.
}

What might be the problem to this?

Create html DOM element using object in javascript without jQuery

I’m wondering if there is an “easy” way to create a big DOM object by specifying the attributes in a json?

I know it’s possible to do this with appendChild and/or innerHTML, but for this object in question, it looks quite messy.

The goal is to create this HTML object from the bottom up in javascript:

<div className="p-2">
    <div className="d-flex p-2 bg-dark2-35">
        <div className="Popover h-3">
            <div className="pfp" style="background-image: url('/data/images/PP/1.png')"></div>
        </div>
        <div className="d-grid ms-2 w-100">
            <p><b className="lead text-blue">Username</b> — <i>2020-01-16 19:29:34</i></p>
            <p className="text-white">some comment text</p>
        </div>
    </div>
</div>

I was wondering if it’s possible to do something like this (I know it doesn’t work):

let comment = document.getElementById("comment-section");
let elm = {
    className: "p-2",
    appendChild(node) {
        classList.add("d-flex", "p-2", "bg-dark2-35"),
        appendChild(node2){
            classList.add("Popover", "h-3"),
            // ... and so on
        }
    }
}
comment.appendChild(elm);

Is there an easy way to do this in pure JS? Would I have to make a function to achieve this? or maybe go as far as to import a library?

The question is a bit similar to Create DOM element from Object in javascript, but I’m completely lost when it comes to this many childrens, with childrens and so on

I’m a bit of a newbie when it comes to JavaScript. The question might come off as strange

Getting all classes from one element and adding them to another element in vanilla JavaScript

I’m trying to get all classes from one element, then add them to another element created dynamically. I was originally stuck on how to do this, but as I was typing out this question, I worked out a solution. However, it seems a bit verbose. Is there a way to do this same thing more efficiently, i.e. with fewer lines of code?

    let classes = this.nextElementSibling.classList;      // get classes from target element
    classes += '';                                        // convert classlist object to string
    let class_array = classes.split(' ');                 // convert string to array
    const my_div = document.createElement('div');         // create a new div
    for(i=0; i<class_array.length; i++) {                 // loop through array and add classes to the div
      my_div.classList.add(class_array[i]);
    }

Thanks in advance.

Using typeof in conditionals is returning the wrong value [duplicate]

I am not well versed in JS at all and am getting ready to pull my hair out regarding this issue. The issue at high level: I have to grab all values from a dropdown and randomly pick one of them to enter in a dropdown field. Then I have to verify if the field value that got saved is the same as the one I entered.

Three values are possible: “True”, “False”, or “None Available”. Where “None” also gets saved as “False” after the fact. Therefore, when the field is saved, only two values are displayed: “True” or “False”.

I have the setup as following:

        let dropdownVal = ["True", "False", "None Available"];
        let randomVal = dropdownVal[Math.floor(Math.random() * dropdownVal.length)];

        //I enter the value resulting from randomVal into the dropdown field using xpath.

        let evalDropdownVal = (typeof randomVal == 'None Available') || (typeof randomVal == 'False') ? "False" : "True"

        //Here I grab the xpath for the "saved" field and evaluate whether the values match.

What keeps happening is, the evalDropdownVal keeps evaluating the opposite. I.e if the value is True, it evaluates it as False and my final matching keeps failing due to that.

I apologize in advance if I butchered the format of the question or didn’t give enough information.

Change page background when hovering over a link

I want to have two different links and when hovering over one it changes the entire PAGE background to a different background-image-url. Then when I hover over the second link it changes the background-image-url to another picture. Is this possible? I am using Angular, I was thinking at first I could do this in css but I now think something more will be required. Any guidance would be greatly appreciated.

how can i add input value to state in React.js?

im trying to get input value and push it into state when the person click on submit,
but i confused.

const App = () => {
    const [category,setCategory] = useState([])
    return ( 
        <div>
            <input type="text" name="" id="" />
            <button type="submit" >Add</button>
        </div>
     );
}
 
export default App;

i tried lot of ways but i coudn’t find any solution.

Upload image to mock-up for HTML canvas

What I want?
When you upload an image to a mock-up such as a model, it’ll put the image in front of the mock-up. For example –

Before uploading the image: https://gyazo.com/83ef496f7c7645e694f35dd0ee5a8ff0

After uploading the image: https://gyazo.com/09c0e4eba05f8959407847e7c713f1ac

As you can see, before it just displays a standard model with the t-shirt on the HTML canvas but after uploading an image, it uploads the image to a specific point on the canvas so it can put the image at that certain point.

So explaining in steps:

Step 1; Upload the image
Step 2; it attaches to the t shirt for example (somehow draws it in HTML canvas)

So my main question stands, if I have a random mock-up from google images such as the one displayed for the before the image was added (https://gyazo.com/83ef496f7c7645e694f35dd0ee5a8ff0) how can make it so it puts any image I upload on a specific section of that model while it blends the image so it looks like it’s part of that mock-up.

google visualization – Creating a table chart and category filter

I am very new to javascript, google app script and google visualization so apologies if my questions are a bit elementary.

My use case:
I am building a web app for yoga company where members are suppose to keep track of their training progress for 21 days. I am using google forms to capture their training progress. For each of the 21 days, there is a google form and responses from the forms are captured into a google spreadsheet. Once the member completes each day, he/she can click on the “My Progress” button to see their progress till date.

The next piece of the web app is that when the yoga instructor logs into the web app, he or she should see all of their members for that given center. Then using the category filter, I want to be able to allow the yoga instructor to select which members are 1 day behind schedule, 2 days behind schedule or greater than 2 days behind schedule.

My issue is that once a member gets caught back up, then he or she should not appear on the late list. I am not sure how to do this.

I have add my code for reference. Any help would be so appreciated.

Complete code in the JSFiddle Link

function setChartView ()

{// Begin of function setChartView ()

 var state = columnFilter.getState().selectedValues;
 var row;
 var view  = {
        columns: [0]
    };

var viewFilters = [];


console.log ("Display state.length:  " + state.length)
console.log ("Display value for state:  " + columnFilter.getState().selectedValues)

tableChart.setDataTable(memberView)

  if ((state.length > 0) && (columnFilter.getState().selectedValues == "Greater Than 2 Days Behind Schedule" ))
     {// Begin of IF Statement for ((state.length > 0) && (columnFilter.getState().selectedValues == "Greater Than 2 Days Behind Schedule" ))

        //console.log ("Display inside the IF statement for (state.length > 0) && (columnFilter.getState().selectedValues == Current Day Not Complete ")
        var daysBehindSchedule = 0

  
        tableChart.setView({rows: centerData.getFilteredRows([{column: 11,
                                                              test: function daysBehindSch (value)
                                                                     {//Begin of function daysBehindSch (value)
                                                                        var actualDayTime = new Date (value)
                                                                        var actualDayTimeStr = actualDayTime.toDateString()
                                                                        console.log ("Display actualDayTime:   " + actualDayTime)
                                                                        var currentDate = new Date()
                                                                        var currentDateStr = currentDate.toDateString()
                                                                        var currentDayFlag = "No"
                                                                        
                                                              
                                                                        console.log ("Display currentDate:   " + currentDate)
                                                                        if (actualDayTimeStr == currentDateStr)
                                                                           {
                                                                             currentDayFlag = "Yes"
                                                                           }

                                                                        if (actualDayTime < currentDate)
                                                                           {
                                                                             daysBehindSchedule = currentDate.getDate() - actualDayTime.getDate() 
                                                                             console.log ("Display daysBehindSchedule:  " + daysBehindSchedule)
                                                                             if (daysBehindSchedule > 2)
                                                                                {
                                                                                  return true
                                                                                }
                                                                             else
                                                                               {
                                                                                 //document.getElementById("errorMsg01").innerHTML = "No members are greater than 2 days behind schedule";
                                                                                 return false
                                                                               }
                                                                           }
                                                                  
                                                                     } //End of function daysBehindSch (value)
                                                                },
                                                                {column: 1,value: '1 - Day'},
                                                                {column: 12,
                                                                 test: function daysCompleted (value)
                                                                       {// Begin of function daysCompleted (value)

                                                                          if (value <= 21)
                                                                            {
                                                                              return true
                                                                            }
                                                                          else
                                                                            {
                                                                              return false 
                                                                            }

                                                                       }// End of function daysCompleted (value)
                                                                }

                                                                ])})

     }// End of IF Statement for ((state.length > 0) && (columnFilter.getState().selectedValues == "Greater Than 2 Days Behind Schedule" )) 
  else if ((state.length > 0) && (columnFilter.getState().selectedValues == "2 Days Behind Schedule" ))
     {// Begin of ELSE IF statement for ((state.length > 0) && (columnFilter.getState().selectedValues == "2 Days Behind Schedule" ))
       tableChart.setView({rows: centerData.getFilteredRows([{column: 11,
                                                               test: function daysBehindSch (value)
                                                                     {//Begin of function daysBehindSch (value)
                                                                        var actualDayTime = new Date (value)
                                                                        console.log ("Display actualDay:   " + actualDayTime)
                                                                        var currentDate = new Date()
                                                                        if (actualDayTime < currentDate)
                                                                           {
                                                                             daysBehindSchedule = currentDate.getDate() - actualDayTime.getDate() 
                                                                             console.log ("Display daysBehindSchedule:  " + daysBehindSchedule)
                                                                             if (daysBehindSchedule == 2)
                                                                                {
                                                                                  return true
                                                                                }
                                                                             else
                                                                               {
                                                                                 //document.getElementById("errorMsg02").innerHTML = "No members are 2 days behind schedule";
                                                                                 return false
                                                                               }
                                                                              
                                                                           }
                                                                        
                                                                        
                                                                     } //End of function daysBehindSch (value)
                                                                },
                                                                {column: 1,value: '1 - Day'},
                                                                {column: 12,
                                                                 test: function daysCompleted (value)
                                                                       {// Begin of function daysCompleted (value)

                                                                          if (value <= 21)
                                                                            {
                                                                              return true
                                                                            }
                                                                          else
                                                                            {
                                                                              return false 
                                                                            }

                                                                       }// End of function daysCompleted (value)
                                                                }

                                                                ])})
     } // End of ELSE IF statement for ((state.length > 0) && (columnFilter.getState().selectedValues == "2 Days Behind Schedule" ))
  else if ((state.length > 0) && (columnFilter.getState().selectedValues == "Current Day Not Complete" ))

     {// Begin of ELSE IF Statement for ((state.length > 0) && (columnFilter.getState().selectedValues == "Current Day Not Complete" ))
                 tableChart.setView({rows: centerData.getFilteredRows([{column: 11,
                                                               test: function daysBehindSch (value)
                                                                     {//Begin of function daysBehindSch (value)
                                                                        var actualDayTime = new Date (value)
                                                                        console.log ("Display actualDay:   " + actualDayTime)
                                                                        var currentDate = new Date()
                                                                        if (actualDayTime < currentDate)
                                                                           {
                                                                             daysBehindSchedule = currentDate.getDate() - actualDayTime.getDate() 
                                                                             console.log ("Display daysBehindSchedule:  " + daysBehindSchedule)
                                                                             if (daysBehindSchedule == 1)
                                                                                {
                                                                                  return true
                                                                                }
                                                                             else
                                                                               {
                                                                                 //document.getElementById("errorMsg03").innerHTML = "Members have completed current day";
                                                                                 return false
                                                                               }
                                                                              
                                                                           }
                                                                        
                                                                     } //End of function daysBehindSch (value)
                                                                },
                                                                {column: 1,value: '1 - Day'},
                                                                {column: 12,
                                                                 test: function daysCompleted (value)
                                                                       {// Begin of function daysCompleted (value)

                                                                          if (value <= 21)
                                                                            {
                                                                              return true
                                                                            }
                                                                          else
                                                                            {
                                                                              return false 
                                                                            }

                                                                       }// End of function daysCompleted (value)
                                                                }

                                                                ])})

     }// End of ELSE IF Statement for ((state.length > 0) && (columnFilter.getState().selectedValues == "Current Day Not Complete" ))

  else 
     { // Begin of ELSE Statement for ((state.length > 0) && (columnFilter.getState().selectedValues == "Greater Than 2 Days Behind Schedule" ))

         tableChart.setView({rows: centerData.getFilteredRows([{column: 1,value: '1 - Day'}])}, {columns: memberView.setColumns([0,8,9])})

     } // END of ELSE Statement for ((state.length > 0) && (columnFilter.getState().selectedValues == "Greater Than 2 Days Behind Schedule" ))
    
    tableChart.draw();

}// End of function setChartView ()

google.visualization.events.addListener(columnFilter, ‘statechange’, setChartView);

setChartView();
columnFilter.draw();

}// End of drawCenterDashboard ()

} // End of function createCenterDashboard (output1)

random link on button press keeps concatenating

(sorry if the title sucks i spent like 30 minutes trying to word i physicaly cant like what do you put)

hey guys so i have this code here and the goal is that i can generate a random newgrounds song every time the generate button is clicked. i can get it working without noticeable flaws (unless you click the scroll wheel to make a new tab in which case the illusion will fail) but the problem is that i wanted it to work without needing a refresh. so i made the button create a new tab instead but now it appends the random number and ive ran out of question i can ask google so can someone either help me fix the fact it appends the number to the new link and not the base link or help me make the goal of a random newgrounds link generator in a more efficient way? if anything here looks bad then just know i am a beginner when it comes to html and javascript i spent most of my coding life on scratch. if some of the code looks good then i probably copied it

<!DOCTYPE html>
<html> 

<head> 
<link rel="stylesheet" href="CSS1.css">

<script>
  window.onclick = () => {
    document.querySelectorAll("a").forEach(link =>
     link.setAttribute("href", link.getAttribute("href") + Math.floor(Math.random() * 111392.8) + 1)
    );
  };
</script>

</head>

<title>
Newgrounds Song Generator
</title> 

<body>

<h1>Click the button to visit a random song!</h1>

<a href="https://www.newgrounds.com/audio/listen/" target="_blank">
<button>
Generate
</button>
</a>

</body>

</html>

Hide/Show div and then hide all div

I am trying to make a “meet the staff” section that has hidden bios that display on click. Right now the div displays as it should, but only disappears when the original button is clicked again. I am needing some additional javascript to hide any opened divs when a different (or same) button is clicked. I don’t know enough javascript to know what to try in order to make this happen. Thanks in advance!

HTML

<div id="lastname" class="toggle-div" style="display: none;">
     <div><p>bio</p>
     </div>
</div>
        
<button class="bio-button" onclick="myBiof()">Click for Bio</button>

Javascript

<script>
function myBiof() {
  var y = document.getElementById("lastname");
  if (y.style.display === "block") {
    y.style.display = "none";
  } else {
    y.style.display = "block";
  }
}

</script>

Where do generic fetch() calls go in React / Redux?

By generic I mean the fetch() call is not tied to a single component.

Where should I put this fetch() call. Currently I have it in the top level React component. I simply return null and it does not render anything but it does run and populate redux.

This method seems a bit hacky and was wondering if React provides a way, or their is a common design pattern, to say fetch data that is not tied to a component.

In general how should I do this?

I would like to write a simple JavaScript function, and then disptach() the data to redux, but React will not let me use dispatch inside a non-rendered JS function.

In general how does one write fetch() when the fetch() is not tied to a single component, and when this fetch() should use a dispatch().

// hacky way
import React                from 'react';
import { useDispatch }      from 'react-redux';

export default () => {

  const dispatch = useDispatch();
  // run fetch() here
  return null;
};

How to dispatch Javascript custom events from a custom object

I have 2 scripts (Extremely simplified examples below) – The first controls the display of a specified nav menu on a page and it us used in several places for different kinds of menus.

const NavMenu = function(selector) {
  this.menuItems = document.querySelectorAll(`${selector} li > a`);
  let This = this;      
  This.menuItems.forEach(item => {
    item.addEventListener('click', e => {
        item.classList.toggle('selected'); 
    });
  });
}

const myNavMenu = new NavMenu('.menu-wrap'); 

The other is used for 1 specific purpose on a specific page containing a menu that is controlled by the 1st script.

(function () {
   const menuItems = document.querySelectorAll('.menu-wrap li > a');
   menuItems.forEach(item => {
     item.addEventListener('click', e => {
         const selectedItems = document.querySelectorAll('.menu-wrap li > a.selected');
         let str = '';
         if(selectedItems.length) {
           selectedItems.forEach((item, i) => {
             str += `${item.textContent} `;
           });
           document.querySelector('#results').innerText = `Selected: ${str}`;
         }
       });
   });
 })();

As you can see, the 2nd script has a click handler that performs an action based on the state of each menu item (“selected” or not). Since that state is set by the 1st script, this only works if 1st script’s click handler runs BEFORE the 2nd.

I created a version where I force the 2nd script’s click handler to run first(via setTimeout). Clicking on the items, you can see that the resulting text does not match.
https://codepen.io/daveh0/pen/GROXmrq

Because the 1st script is used in many other places, it needs to run independently of any other script, otherwise I would have just combined the 2.

I think a custom event is the answer here. i implemented one here: https://codepen.io/daveh0/pen/xxPaqzJ from an example I found, but I have no idea if this is the correct way to do it. It works, but that doesn’t mean a ton…

I’d think the event should be somehow tied to the NavMenu object, but I couldn’t get it to dispatch from anything other than window or document or another DOM element. Can anyone point me in the right direction for a way that I can do something like: myMenu.addEventListener('done', e => //do some stuff) rather than having it attached to window? Or if I’m way off to even begin with, feel free to let me know as much too.

I know this is kind of built into jQuery, but this needs to stay Vanilla JavaScript – thanks!

How can I pass properties from a mapped Div to a function when a button is clicked?

I am mapping cards from an array in divs using the map() function, and I am trying to have each div include a button that will make a post request to an api. Each card in the array has a card id, which I am able to display when creating the divs using “card.id”. When I press the button, however, the addToCollection2 function is telling me that “card.id” is undefined. Can anyone tell me why it is said to be undefined?

Here is the html code:

<div className="cardImages">
        {cardsFetched ? (
          cards.data.map((card) => (
            <div className="searchedCards" key={card.id}>
              <div className="singleCard">
                <img src={card.images.small} />
                <p>Card ID : {card.id}</p>
                <button onClick={() => addToCollection2(card.id)}>
                  Add Card
                </button>
              </div>
            </div>
          ))
        ) : (
          <div>Searched cards will appear below</div>
        )}
      </div>

Here is the addToCollection2() JavaScript function:

async function addToCollection2(cardId) {
    //e.preventDefault;
    console.log(cardId);
    try {
      const body = { collection_id, cardId };
      const response = await fetch("https://tcgdex.herokuapp.com/collection", {
        mode: "cors",
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      console.log(response);
    } catch (err) {
      console.error(err.message);
    }
    return false;
  }

How to make clickable Header in React

I am trying to make my Header clickable to navigate to homepage but the code below is not working, I’m sure that there should be a really easy way to do it.

const Header = () => {
  const navigate = useNavigate()

  return (
    <div>
      <h1 className="font-weight-light display-1 text-center" onClick={navigate('/')}>
        The X app
      </h1>
    </div>
  )
}