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.

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>
  )
}

Passing data up through nested functions in .js

Coding beginner here. I’ve got a page-js script below which when a dropdown is changed it triggers function getDrawNumOne, which in turn runs a function and retrieves two pieces of data from a GoogleSheet (drawNumReturnOne[0] & [1]). I want to pass the returned drawNumReturnOne[1] up through getDrawOneNum and then on into doStuff for use there – but am struggling on how to do this in a slick way, given I cannot call variables outside of their function scope. Do I need multiple returns up through the function stack or is there another, better way? All advice gratefully accepted, thanks.

document.getElementById("btn").addEventListener("click",doStuff);
document.getElementById("m_p1").addEventListener("onchange",getDrawNumOne);
   
function doStuff(){    
   var userInfo ={};
   userInfo.m_p1 = document.getElementById("m_p1").value;
   userInfo.m_s1 = ######;
   google.script.run.userClicked(userInfo);
    
   }
   
function getDrawNumOne(){
var drawNumOne = document.getElementById("m_p1").value;
   google.script.run.withSuccessHandler(updateDrawNumOne).getDrawNo(drawNumOne); 
   
}
function updateDrawNumOne(drawNumReturnOne){
   document.getElementById("draw1").value = drawNumReturnOne[0];
   ###### = drawNumReturnOne[1];
}

How to filter in grpahql github api by MergeableState

So I have the following block of code that returns me list of PR with their mergeability status such as ‘MERGEABLE’, ‘CONFLICTING’, etc. I want to understand if there is anyway to filter inline by mergeablestate. I can filter the result obtained after this using js or anything else. I wanted to understand for any way to do it directly in graphql script. Looked up the docs could not find a way

{
      repository(owner: "fireship-io", name: "git-sticker") {
        pullRequests(first: 1, states: [OPEN]) {
          nodes {
            id
            number
            changedFiles
            deletions
            mergeable
            author {
              url
            }
          }
        }
      }
    }

I tried

pullRequests(first: 1, states: [OPEN], mergeable: [MERGEABLE))

But got an error saying mergeable is not a valid argument for pullRequests.

Alpine.js – show/hide div based from select input values

I’m trying to show and hide div’s based from a select box selected value. I have my select boxes working so that it changes the value like so:

// x-data="{ week: false, day: false }

            <select @change="week = $event.target.value">
                <option x-bind:value="Week 1">Week 1</option>
                <option x-bind:value="Week 2">Week 2</option>
                <option x-bind:value="Week 3">Week 3</option>
            </select>
            <select @change="day = $event.target.value">
                <option x-bind:value="1">Monday</option>
                <option x-bind:value="2">Tuesday</option>
                <option x-bind:value="3">Wednesday</option>
                <option x-bind:value="4">Thursday</option>
                <option x-bind:value="5">Friday</option>
            </select>
            <span x-text="'option '+ week"></span>
            <span x-text="'option '+ day"></span>

I am then trying to show and hide divs based on the selections like so, but having no luck.

<div :class="week !== {{ $week['name'] }} ? 'hidden' : 'block'">
     <p>{{ $week['name'] }}</p>
</div>

How can I correctly set the class?