How to setAttribute value with url? [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I am setting a url to a DOM of a website. Now I could done it by copying the actual url, as below:
document.getElementById('mediaWebUrl').setAttribute('value','https://www.youtube.com/watch?v=hkOTAmmuv_4');
It is not convenient enough. I want to substitute the actual url with a variable. like below:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0];
var videoUrl = activeTab.url; // or do whatever you need
});
But when I do the job as below:
document.getElementById('mediaWebUrl').setAttribute('value',videoUrl);
it didn't succeed and nothing happened. Why? I confirmed the type of the variable "videoUrl" is a string using alert(typeof videoUrl). As neophyte in Javascript, I really need advice in this simple question. Thank you.

You can write a function and pass the value of the id of the div (where you want to display the video) and the video url, and then call the function to set the attribute.
Sample code:
function setVal(id, val){
var el = document.getElementById(id); //get the element
var attrVal = val; //set the url
el.setAttribute('value', val) //set the value to the url
}
setVal("myVid", "https://www.youtube.com/watch?v=hkOTAmmuv_4"); //call the function
(in this case, myVid is the id)
Your code probably didn't worked because the variable was only locally defined.
You can use your web console to check for errors.
Hope this helps!

Related

How to store a newly created element to localStorage or Cookie with Javascript?

I am making an idle clicker game for fun, everything was going fine until I encountered a problem.
What I basically want to happen is when the image is clicked and the clickCounter element is over one, the new image element is created. No problem here, the main problem is saving the image. If the user refreshes the page, I want the created element to still be there. I have tried using outerHTML and following some other Stack Overflow forum questions but I could never get a proper solution to this certain problem. I have also tried localStorage and cookies but I believe I am using them wrong.
My code is below, my sololearn will be linked below, consisting of the full code to my project.
function oneHundThou() {
var countvar = document.getElementById("clickCounter")
if(document.getElementById("clickCounter").innerHTML > 1) {
alert("Achievement! 1 pat!")
var achievement1k = document.createElement("img");
// create a cookie so when the user refreshes the page, the achievement is shown again
document.cookie = "achievement1k=true";
achievement1k.src = "https://c.pxhere.com/images/f2/ec/a3fcfba7993c96fe881024fe21e7-1460589.jpg!d";
achievement1k.style.height = "1000px"
achievement1k.style.width = "1000px"
achievement1k.style.backgroundColor = "red"
document.body.appendChild(achievement1k);
oneHundThou = function(){}; // emptying my function after it is run once instead of using a standard switch statement
}
else {
return
}
}
oneHundThou();
I am aware that there is another post that is similar to this, however, my answer could not be answered on that post.
Full code is here: https://code.sololearn.com/Wwdw59oenFqB
Please help! Thank you. (:
Instead of storing the image, try storing the innerHTML, then create the image on document load:
function oneHundThou() {
countvar.innerHTML = localStorage.getItem('clickCount') ? localStorage.getItem('clickCount') : 0; //before if
//original code
localStorage.setItem('clickCount', countvar.innerHTML); //instead of doc.cookie
}
window.addEventListener('DOMContentLoaded', (event) => {
oneHundThou();
});
or, if you don't care that clickCounter may initialize to null, you can remove the ? : and just put
countvar.innerHTML = localStorage.getItem('clickCount');
Edit: shortened code with the countvar variable

Setting a global variable inside a JS onload() function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I want to store the length of a Json array as a global variable to make my code more modular. I am trying to set the global variable inside the .onload function but it won't allow this. I have tried with a globalTest variable.
var objectLength = 0;
var globalTest = 0;
$(document).ready(function() {
establishConnection();
});
function establishConnection() {
xttp = new XMLHttpRequest();
xttp.open("GET", "http://exampleServerPath", true);
xttp.send("null");
xttp.onload = function() {
var Json = JSON.parse(this.response);
objectLength = Json.length;
globalTest = 2; // this doesn't work
};
globalTest = 4; //this works
}
I am fairly new to JS any help is appreciated!
I think the issue lies with the xttp.onload part. Change that to xttp.onreadystatechange and then check the readystate.
Check out this example.
EDIT:
Your code works as expected, but maybe you think globalTest is not being updated.
If you were to call establishConnection() and then immediately try to access globalTest it will still be 0 because the AJAX request has not completed yet.
If you did
establishConnection();
setTimeout(function() {
alert(globalTest);
}, 2000);
Then you should see the value you expect (assuming your ajax request completes in less than 2 seconds.

Jquery code to check internet connection and change the button as per result [duplicate]

This question already has answers here:
How to detect online/offline event cross-browser?
(15 answers)
Closed 8 years ago.
Jquery Code which check the internet/network is there or not(mobile/PC/Tablet).It must just check on page load.I thinkAjax will good because Ajax will check after certain interval.
I am looking just like http://tomriley.net/, But it is plugin, I am looking for simple jquery/Javascript.
Its static page which check system internet only.
Any idea is appreciated.
You might try a $.ajax() invoication with a .fail() handler, for example JQuery's getJSON():
var network_available; // bool
var url = '/some/json/call'; // must be relative to the site that
// you are already addressing
$.getJSON(url, function(data) {
network_available = true;
})
.fail(function() {
network_available = false;
});
Though I doubt this will solve all of your problems. The Javascript engine won't allow 'foreign' URL's, just the domain that the script or page was received from. So you'd not be really testing network availability, but also whether your site is up and responding within a reasonable time.

Changing url parameter with js without reloading page on button click [duplicate]

This question already has answers here:
How do I modify the URL without reloading the page?
(20 answers)
Closed 8 years ago.
is it possible to change parameter in url bar so button onclick the parameter to get changed ? So far I have this:
function change_product(){
var url = 'http://www.example.com/index.php?product=805';
var newSrc = '0';
newurl=url.replace(/(product=)[^\&]+/,'$1' + newSrc)
alert(newurl);
}
<button class="save" type="BUTTON" onclick="change_product();">Copy</button>
newurl is correct but how to make it change in the url bar? Is it possible at all without page reload?
thanks in advance !
Take a look at window.history.pushState()
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
This allows you to change the URL in the address bar without reloading the page.
Here's the current support: http://caniuse.com/#search=pushstate
var state = {}, newUrl = "test.html";
window.history.pushState(state, "Page Title", newUrl);
So for you something like
function change_product(){
var productId = 805;
window.history.pushState({productId: productId} , "", "?product=" + productId);
}
Firefox currently does use the Page Title but you could set it in the state object then use window.onpopstate to get the state object and set the page title (if you need to).
If you need to support older IE browsers there's a few libraries that can help you out (like history.js)

Node.JS: How to pass variables to asynchronous callbacks? [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
I'm sure my problem is based on a lack of understanding of asynch programming in node.js but here goes.
For example: I have a list of links I want to crawl. When each asynch request returns I want to know which URL it is for. But, presumably because of race conditions, each request returns with the URL set to the last value in the list.
var links = ['http://google.com', 'http://yahoo.com'];
for (link in links) {
var url = links[link];
require('request')(url, function() {
console.log(url);
});
}
Expected output:
http://google.com
http://yahoo.com
Actual output:
http://yahoo.com
http://yahoo.com
So my question is either:
How do I pass url (by value) to the call back function? OR
What is the proper way of chaining the HTTP requests so they run sequentially? OR
Something else I'm missing?
PS: For 1. I don't want a solution which examines the callback's parameters but a general way of a callback knowing about variables 'from above'.
Your url variable is not scoped to the for loop as JavaScript only supports global and function scoping. So you need to create a function scope for your request call to capture the url value in each iteration of the loop by using an immediate function:
var links = ['http://google.com', 'http://yahoo.com'];
for (link in links) {
(function(url) {
require('request')(url, function() {
console.log(url);
});
})(links[link]);
}
BTW, embedding a require in the middle of loop isn't good practice. It should probably be re-written as:
var request = require('request');
var links = ['http://google.com', 'http://yahoo.com'];
for (link in links) {
(function(url) {
request(url, function() {
console.log(url);
});
})(links[link]);
}
Check this blog out. A variable can be passed by using .bind() method. In your case it would be like this:
var links = ['http://google.com', 'http://yahoo.com'];
for (link in links) {
var url = links[link];
require('request')(url, function() {
console.log(this.urlAsy);
}.bind({urlAsy:url}));
}
See https://stackoverflow.com/a/11747331/243639 for a general discussion of this issue.
I'd suggest something like
var links = ['http://google.com', 'http://yahoo.com'];
function createCallback(_url) {
return function() {
console.log(_url);
}
};
for (link in links) {
var url = links[link];
require('request')(url, createCallback(url));
}

Categories

Resources