Javascript / JQuery Set Cookie on page load - javascript

I would appreciate some orientation in the following issue.
I want to set a cookie when a page loads. The cookie value should taken from a div data-myifo attribute within the HTML code.
My current code looks as follows:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id=someid data-myinfo="yyyyy">Hello World</div>
<script type="text/javascript">
function set_cookie (cookieName,cookieValue,nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString()
+ "; path=/";
}
function get_atribute () {
var myinfo = document.getElementsByTagName("div")[0].getAttribute("data-myinfo");
set_cookie ("My_Cookie", myinfo);
}
$(document).ready(function () {
get_atribute ();
});
</script>
</body>
</html>
I've tried running the function get_atribute () using a onclick="get_atribute ()" and that way it works but not on page load or after.
What am I missing?

No need to use jQuery here
Could just use:
(function() {
get_attribute();
})();

Related

Why can I write to sessionStorage from an iframe on the first try, but not any consecutive tries? (Chrome Version 74)

This issue has shown up in the latest version of Chrome (74.0.3729.108). This is unique to the local filesystem, as I have other ways of loading up neighboring documents in iframes when the app is on a server.
In my app, we have been able to load up documents from the filesystem with JavaScript by writing iframes to the DOM, and then having the document in the iframe write it's innerHTML to sessionStorage. Once the iframe is done loading, we catch that with the onload attribute on the iframe and handle getting the item written to sessionStorage.
I have narrowed this down to some bare-bones code and found that this works only on the first try, and then any tries after the first fail.
Here is a minimal HTML document:
<!DOCTYPE html>
<html>
<head>
<title>Chrome iFrame Tester</title>
<script src="iframe-load.js"></script>
</head>
<body onload="OnLoad()">
<div id="result"></div>
</body>
</html>
Here is the JavaScript:
var urls = ['file://C:/Users/afrench/Documents/Other/Misc%20Code/Chrome%20iFrame/Doc1.html',
'file://C:/Users/afrench/Documents/Other/Misc%20Code/Chrome%20iFrame/Doc2.html'];
HandleLoad = function () {
'use strict';
var data;
try {
data = window.sessionStorage['data'];
delete window.sessionStorage['data'];
} catch (ignore) {
// something went wrong
}
var container = document.getElementById('container');
window.document.body.removeChild(container);
if (data !== null && data !== undefined) {
var resultContainer = document.getElementById('result');
resultContainer.innerHTML += data;
}
if (urls.length > 0) {
OnLoad();
}
}
function OnLoad() {
var url = urls[0];
if (url) {
urls.splice(0, 1);
var container = document.createElement('div');
container.id = 'container';
container.style.visibility = 'hidden';
window.document.body.appendChild(container);
container.innerHTML = '<iframe src="' + url + '" onload="HandleLoad();"></iframe>';
}
}
In the filesystem, we have the HTML written into index.html, and right next to it are two minimal HTML files, Doc1.html and Doc2.html. Their contents are both identical except the identifying sentence in the body's div:
Neighbor document HTML:
<!DOCTYPE html>
<html>
<head>
<title>Chrome iFrame Tester</title>
<script>
function OnLoad() {
try {
window.sessionStorage['data'] = window.document.body.innerHTML;
} catch {
// no luck
}
}
</script>
</head>
<body onload="OnLoad()">
<div>This is Doc 1's content!</div>
</body>
</html>
When this is run, we should see the content HTML of the two neighbor documents written to the result div in index.html.
When I run this minimal example, I can see that the content is successfully written to sessionStorage and then to the DOM for the first document, but the next try fails. What can I do to get it to work consistently, and what is happening here that it fails?
I'm not sure what is causing the weird behavior, so hopefully someone else can provide some insight on what exactly is going on here.
In the meantime, here is an alternative solution using window.postMessage:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Chrome iFrame Tester</title>
<script src="iframe-load.js"></script>
</head>
<body onload="OnLoad()">
<div id="result"></div>
</body>
</html>
iframe-load.js
var urls = ['file://C:/Users/afrench/Documents/Other/Misc%20Code/Chrome%20iFrame/Doc1.html',
'file://C:/Users/afrench/Documents/Other/Misc%20Code/Chrome%20iFrame/Doc2.html'];
window.addEventListener('message', event => {
'use strict';
var data = event.data;
var container = document.getElementById('container');
window.document.body.removeChild(container);
if (data) {
var resultContainer = document.getElementById('result');
resultContainer.innerHTML += data;
}
if (urls.length > 0) {
OnLoad();
}
})
function OnLoad() {
var url = urls.shift();
if (url) {
var container = document.createElement('div');
container.id = 'container';
container.style.visibility = 'hidden';
window.document.body.appendChild(container);
container.innerHTML = '<iframe src="' + url + '"></iframe>';
}
}
Doc1.html
<!DOCTYPE html>
<html>
<head>
<title>Chrome iFrame Tester</title>
<script>
function OnLoad() {
window.parent.postMessage(window.document.body.innerHTML, '*');
}
</script>
</head>
<body onload="OnLoad()">
<div>This is Doc 1's content!</div>
</body>
</html>

Input that searches google

I am making a extension theme for my Chromebook that searches coding sites (like this site, w3schools, ect.) How sould I make it? This is my code so far:
<html>
<head>
</head>
<body>
<input id="input1">
<button onclick="searchGoogle()">Search Google</button>
<script>
function searchGoogle() {
var one = document.getElementById("input1").value;
var two = 'http://www.google.com/search?q=' + one;
window.location = two;
}
</script>
</body>
</html>
My code doesn't work
When it runs, this pops up:
(Image of my code running)
Is my code wrong?
Any help will be aapreciated.
EDIT
<html>
<head>
<script src="searchgoogle.js">
</script>
</head>
<body>
<input id="input1">
<button id="link">Search Google</button>
</body>
</html>
and
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('link');
// onClick's logic below:
link.addEventListener('click', function() {
function searchGoogle() {
var one = document.getElementById("input1").value;
var two = 'https://www.google.com/search?q=' + one;
window.location = two;
}
});
});
Didn't work either
You declare the function searchGoogle inside the listener function but it is never called. Try with:
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('link');
// onClick's logic below:
link.addEventListener('click', function() {
//there is no need to declare a new function here.
var one = document.getElementById("input1").value;
var two = 'https://www.google.com/search?q=' + encodeURIComponent(one);
window.location = two;
});
});

Javascript drop down works in jsfiddle but not in html file

I am trying to get minutes in drop down using javascript.
in JSfiddle it works however when I use it in my page it doesn't.
Here is my code.
<html>
<head>
<script src="js/jquery.js" ></script>
<script type="text\javascript">
function myFunction() {
var minutes = [],
select = document.getElementById( 'minutes' );
for( minutes=1;minutes<=59;minutes++ ) {
select.add( new Option(minutes) );
};
</script>
</head>
<body>
<p>
<select id="minutes"></select>
</p>
</body>
</html>
The slash direction is wrong. Should be text/javascript not text\javascript
Also move the contents of the function to the global scope.
You need to wrap the code in $(document.ready() like below:
Also, you need to call myFunction, which I don't see.
Additionally, modify <script type="text\javascript"> to <script type="text/javascript">
$(document).ready(function () {
function myFunction() {
var minutes = [],
select = document.getElementById('minutes');
for (minutes = 1; minutes <= 59; minutes++) {
select.add(new Option(minutes));
};
}
myFunction();//<---Call here
});

Javascript function checking dates

Hi I am new to Javascript and am trying to create a function that checks two dates. I have read it is useful to put the JS in the head part of the document, but this is not returning anything. I am also new to stackoverflow so I hope I did this correctly. :) Does anyone see the error?
<!DOCTYPE html>
<html>
<head>
var myDate = new Date(); // Your timezone!
var myEpoch = myDate.getTime()/1000;
var deadline = '1341596750.000';
document.write(myEpoch);
document.write("<br>",deadline);
if (myEpoch < deadline) {
document.write("<p>Just in time!</p>");
} else {
document.write("<p>Too late!</p>");
}
</head>
<body>
<br><br><br><br>http://www.epochconverter.com/
</body>
</html>
You have to mention it's a script using <script>. Also you shouldn't output DOM in the <head> like you are doing with document.write. Manipulate the DOM like this instead:
<head>
<script type="text/javascript">
var myDate = new Date(); // Your timezone!
var myEpoch = myDate.getTime()/1000;
var deadline = '1341596750.000';
document.write(myEpoch);
document.write("<br>",deadline);
if (myEpoch < deadline) {
document.getElementById("useme").innerHTML("Just in time!");
} else {
document.getElementById("useme").innerHTML("Too late!");
}
</script>
</head>
<body>
<p id="useme"></p>

Maintain div scroll position on postback with html/javascript

Is there a way to maintain the div scroll position on a postback, without using asp? So far I've only found solutions using asp.
http://blogs.x2line.com/al/articles/156.aspx
<!doctype html>
<html>
<head>
<title></title>
<script language="javascript">
// function saves scroll position
function fScroll(val)
{
var hidScroll = document.getElementById('hidScroll');
hidScroll.value = val.scrollTop;
}
// function moves scroll position to saved value
function fScrollMove(what)
{
var hidScroll = document.getElementById('hidScroll');
document.getElementById(what).scrollTop = hidScroll.value;
}
</script>
</head>
<body onload="fScrollMove('div_scroll');" onunload="document.forms(0).submit()";>
<form>
<input type="text" id="hidScroll" name="a"><br>
<div id="div_scroll" onscroll="fScroll(this);" style="overflow:auto;height:100px;width:100px;">
.. VERY LONG TEXT GOES HERE
</div>
</form>
</body>
</html>
Maybe this javascript code works for you
function loadScroll ()
{
var m = /[&?]qs\=(\d+)/.exec (document.location);
if (m != null)
myDiv.scrollTop = parseInt (m[1]);
}
function saveScroll ()
{
var form = document.getElementById ("myForm");
var sep = (form.action.indexOf ("?") == -1) ? "?" : "&";
form.action += sep + "qs=" + myDiv.scrollTop;
}
Now, you can watch for the "submit" event to save the position in the "action" attribute:
document.getElementById ("myForm").addEventListener ("submit", saveScroll, false);
And in your BODY tag...
<body onload="loadScroll ();">
....
</body>
I can't test the code right now, but I think you get the idea.

Categories

Resources