Button click if specific url - javascript

I'm trying to make sure that when going to a certain url, the button that is on the page is pressed, but for some reason it doesn't work.
<script>
let loginInp = document.querySelector('.login-form--hide');
let emailInp = document.querySelector('.email-form--hide');
let sendInp = document.querySelector('.send-form--hide');
let loginLoc = window.localStorage.getItem('name');
let emailLoc = window.localStorage.getItem('email');
document.addEventListener("DOMContentLoaded", () => {
if (window.location.href === 'https://url/success/') {
loginInp.value = loginLoc;
emailInp.value = emailLoc;
console.log('Worked');
//sendInp.click();
}
});
</script>
What am I doing wrong?

Related

Make function delete

I recently tried to make a page that saves the input and displays it on the page. Everything works but i want to add a delete button at every input, which deletes only one input. I tried so many different ways, but none of them worked. If you have any idea how to solve this, I would be grateful.
Here is the code:
let savedinput = []
Localstoragesaves = localStorage.getItem("Zaznamki")
const Predpomnjenipodatki = JSON.parse(Localstoragesaves)
const DeleteButtonHTML = document.getElementById("izbrisi-gumb")
const userinput = document.getElementById("vnos-pr")
const inputsavebutton = document.getElementById("vnos-gumb")
const LabelHTML = document.getElementById("seznamzaznamkov")
const SaveTab = document.getElementById("zavihek-gumb")
const DeleteLast = document.getElementById("pocisti-zadnjo")
if (Localstoragesaves) {
savedinput = Predpomnjenipodatki
Render(savedinput)
}
DeleteLast.addEventListener('click', function(){
savedinput.pop()
Render(savedinput)
})
SaveTab.addEventListener('click',
function(){
browser.tabs.query({active: true, currentWindow: true}, function(tabs){
savedinput.push(tabs[0].url)
localStorage.setItem("Zaznamki", JSON.stringify(savedinput))
Render(savedinput)
console.log( localStorage.getItem("Zaznamki") )
})
})
function Render(parameter) {
let tabslabel = ""
for (i = 0; i < parameter.length; i++) {
tabslabel += `
<li>
<a href='${parameter[i]}' target='_blank'>${parameter[i]}</a>
</li>
`
}
LabelHTML.innerHTML = tabslabel
}
DeleteButtonHTML.addEventListener('dblclick',
function() {
localStorage.clear()
savedinput = []
LabelHTML.textContent = ''
})
inputsavebutton.addEventListener("click", function(){
const Vsebinavnosa = userinput.value
savedinput.push(Vsebinavnosa)
localStorage.setItem("Zaznamki", JSON.stringify(savedinput))
Render(savedinput)
userinput.value = ""
console.log( localStorage.getItem("Zaznamki") )
})
I solved this problem myself. I'm quite proud 😁. I want to thank you for your really quick responses even if I didnt get the solution here.
If someone has the same problem I had, I will tell you what I did.
In function render, I added a button with onclick function with argument, so that this new function which will be called will know which item from array needs to remove:
<button id="${parameter[i]}" onclick="Delete(${i})">Delete</button>
and then somewhere in this document I added this function which gets value from button click and knows which item from the array savedinput and localstorage needs to remove:
function Delete(parameter) {
mojizaznamki.splice(parameter, 1)
console.log(savedinput)
localStorage.setItem("Zaznamki", JSON.stringify(savedinput))
Render(savedinput)
}
Hope this helps others.
Greetings from Slovenia

How would a nested function look like in this clickHandler()?

I'm stalled with this clicHandler() from this question:
function clickHandler(evt) {
// Activate the circle
activateCircle(evt.target.id);
// Remember which one was clicked, so that we can
// highlight the right one when we get to the subpage
sessionStorage.setItem("selectedMenuId", evt.target.id);
}
The problem is that there are 5 different circles, and I need the clickHandler() to know which one has been clicked and return the correct activateCircle(evt.target.id).
I was thinking about something like this (I might be wrong):
getElementById("c1").onclick = goTransdisciplinary () {
location.href = "/trans-disciplinary";
};
getElementById("c2").onclick = goDatademocracy () {
location.href = "/data-democracy";
};
getElementById("c3").onclick = goCryptography () {
location.href = "/cryptography-and-math";
};
getElementById("c4").onclick = goTranslation () {
location.href = "/translation";
};
getElementById("c5").onclick = goApplication () {
location.href = "/application";
};
But how would a nested function look like?

How can I run javascript file after dom manipulation made in another js file?

When I run my rails application and enter likeButton into the console it gives me Uncaught ReferenceError: likeButton is not defined
at :1:1
(anonymous) # VM1591:1
I tried moving the script in html to head and body. I am currently trying to use DOMContentLoaded but it seems I'm missing something. My overall goal is to change the color of the button once pressed and also keep the color after page refresh. I am using sessionStorage for this process. I just want to make sure that likeButton variable is declared after html is loaded. If its possible to done in javascript only.
//first js file
const BASE_URL = "http://localhost:3000"
const GPUS_URL = `${BASE_URL}/gpus`
const USERS_URL = `${BASE_URL}/users`
const gpuCollection = document.querySelector('#gpu-collection')
let wish = sessionStorage.getItem('wish');
class Gpu {
constructor(gpuAttributes) {
this.title = gpuAttributes.title;
this.price = gpuAttributes.price;
this.features = gpuAttributes.features;
this.link = gpuAttributes.link;
this.image = gpuAttributes.image;
this.id = gpuAttributes.id;
}
render() {
let div = document.createElement('div');
div.classList.add('card');
let h = document.createElement('h2');
let t = document.createTextNode(`${this.title} ($${this.price})`);
h.appendChild(t);
div.appendChild(h);
let h1 = document.createElement('h1');
h1.classList.add('gpu-cat');
h1.innerHTML = `${this.features}`;
div.appendChild(h1);
let button = document.createElement('button');
button.classList.add('list_btn');
button.innerHTML = '♡';
div.appendChild(button);
let a = document.createElement('a');
let img = document.createElement('img');
a.href = `${this.link}`;
a.target = '_blank';
img.src = `${this.image}`;
img.classList.add('gpu-image');
a.appendChild(img);
div.appendChild(a);
gpuCollection.appendChild(div);
}
}
//second js file
document.addEventListener("DOMContentLoaded", function (){
let likeButton;
SignUp();
logInUser();
logOutUser();
function putGpusOnDom(gpuArray){
gpuArray.forEach(gpu => {
let newGpu = new Gpu(gpu)
newGpu.render()
});
likeButton = document.querySelector("button");
}
function fetchGpus(){
fetch(GPUS_URL)
.then(res => res.json())
.then(gpus => putGpusOnDom(gpus))
}
const enableWish = () => {
console.log(likeButton)
sessionStorage.setItem('wish', 'red')
}
gpuCollection.addEventListener('click', function (){
wish = sessionStorage.getItem('wish');
if(wish !== 'red'){
enableWish();
}else{
disableWish();
}
});
})
//html file
...
<body>
<div id = "gpu-collection"></div>
<script type="text/javascript" src="src/Gpu.js"></script>
<script type="text/javascript" src="src/index.js" ></script>
</body>
</html>
As I mentioned in a comment the like button is not available on DOMContentLoaded if it is added dynamically. You need to wait until the button has been placed in the DOM
Use something like the following, I'm making some guesses here as there are some gaps in your code
document.addEventListener("DOMContentLoaded", function (){
//document.querySelector("button"); not yet available
//NOTE: The likeButton variable will ONLY be in scope INSIDE the event listener function
// You will not be able to access directly in the console.
let likeButton;
SignUp();
logInUser();
logOutUser();
function putGpusOnDom(gpuArray){
gpuArray.forEach(gpu => {
let newGpu = new Gpu(gpu)
newGpu.render()
});
//Now you have rendered the button it is available
//CAUTION: querySelector("button") will grab the first button on the page
// and ONLY the first button
likeButton = document.querySelector("button");
//Log like button to console while it is still in scope.
console.log(likeButton);
}
function fetchGpus(){
fetch(GPUS_URL)
.then(res => res.json())
.then(gpus => putGpusOnDom(gpus))
}
const enableWish = () => {
console.log(likeButton)
sessionStorage.setItem('wish', 'red')
}
})

how to get a reference number (form of a link) to auto fill part of a form in another html page using javascript

using local storage and onclick with javascript
I have a html file with 2 job descriptions :
html file 1
<li><Job Reference Number: wru01</li>
<li><Job Reference Number: wru01</li>
I need to create a link (using javascript) that when each job description is clicked it auto fills out the form where the job description should be entered (this form is on another html page)
html file 2:
<legend>Job Application Information: </legend>
<label> Job Reference Number: </label>
<input id="refnumber" type="text" name="refnumber" required="required" />
so basically i need it that, when, and depending on which job number is clicked wru01 or wru02, it auto fills the job reference number in the form on the next page using local storage.
I have already tried this
js file 1
function onclick1() {
var anchor = document.getElementById('link');
anchor.addEventListener('click', function(event) {
event.preventDefault();
const jobCode = event.target.getAttribute('data-job');
localStorage.setItem('job-code', jobCode);
//need redirect user to apply page
//console.log(event.target)
window.location = event.target.getAttribute('href');
})
}
function onclick2() {
var anchor = document.getElementById('link2');
anchor.addEventListener('click', function(event) {
event.preventDefault();
const jobCode = event.target.getAttribute('data-job');
localStorage.setItem('job-code', jobCode);
//need redirect user to apply page
//console.log(event.target)
window.location = event.target.getAttribute('href');
})
}
function init() {
document.getElementById("link").onclick = function() {
onclick1()
};
document.getElementById("link2").onclick = function() {
onclick2()
}
window.onload = init;
}
js file 2
function LoadJobCode() {
var code = localStorage.getItem('job-code');
if (code) {
var input = document.getElementById('refnumber');
// disable text being entered
input.value = code;
input.disabled = true;
}
}
Excuse me,that's not a good idea to do it.I think you can use setTimeout to solve the problem.that's my code:
function onclick1() {
var anchor = document.getElementById('link');
anchor.addEventListener('click', function (event) {
event.preventDefault();
const jobCode = event.target.getAttribute('data-job');
console.log(jobCode)
localStorage.setItem('job-code', jobCode);
setTimeout(() => {
window.location.href = event.target.getAttribute('href');
},1000)
})
}
why did I do that?That's order to make sure to save the data(data-job) before entering another html page.Likewise,you can use async/await,such as below:
function onclick1() {
var anchor = document.getElementById('link');
anchor.addEventListener('click', function (event) {
event.preventDefault();
const jobCode = event.target.getAttribute('data-job');
console.log(jobCode)
localStorage.setItem('job-code', jobCode);
async function locate() {
await new Promise(() => {
window.location.href = event.target.getAttribute('href');
})
}
locate();
})
}

How can I trigger modal boxes using the following javascript code?

Hey guys I need just a little bit of help with this.
So I have modal boxes hiding on my page and when I click on them using the video platform VERSE they work perfectly.
My questions is: How can I call the same modal boxes if I wan to call them from a regular link or button on the page.
Here is the sample:
http://digitalfeast.com/clients/nccv/ncc-verse.html
Here is my Javascript code:
(function() {
(function() {
window.onload = function() {
var frame = document.getElementsByName("verse-iframe")[0].contentWindow;
// Variables below (i.e. "menu-1") reference div id from your markup
function receiveMessage(event) {
var data = (typeof event.data === "String") ? JSON.parse(event.data) : event
var modalWindow1 = document.getElementById("ruben-1");
var modalWindow2 = document.getElementById("ruben-2");
var modalWindow3 = document.getElementById("menu-3");
var modalWindow4 = document.getElementById("menu-4");
// Variables below (i.e. "menu-1") reference the unique callback names entered for your hotspots in the Verse editor
if (data.data["identifier"] === "ruben-1") {
modalWindow1.style.display = "block";
}
if (data.data["identifier"] === "ruben-2") {
modalWindow2.style.display = "block";
}
if (data.data["identifier"] === "menu-3") {
modalWindow3.style.display = "block";
}
if (data.data["identifier"] === "menu-4") {
modalWindow4.style.display = "block";
}
}
var closeBtns = document.getElementsByClassName("modal-close");
for (var i = 0; i < closeBtns.length; i++) {
var btn = closeBtns[i];
btn.onclick = function (event) {
event.target.parentNode.parentNode.style.display = "none";
frame.postMessage({action: "play"}, "*");
};
}
window.addEventListener('message', receiveMessage);
var frame = document.getElementsByName("verse-iframe")[0].contentWindow;
};
}());
}());
Given your code, all you need to do is send the window a message using the Messaging API inside your button click handler.
Your event listener will then execute the receiveMessage function and open your model for ruben-1.
window.onload = () => {
document.querySelector('[data-modal="ruben-1"]').addEventListener("click", (e) => {
let postData = {
identifier: e.target.dataset.modal
};
window.postMessage(postData, "*");
});
window.addEventListener('message', m => {
alert(m.data.identifier);
});
}
<button data-modal="ruben-1">Ruben-1 Video</button>

Categories