How can I random elements order (link), so that they appear every case in other order? here is my js code:
$(document).ready(function(){
if ($.browser.msie && jQuery.browser.version.substr(0,1)<='6' && readCookie('already_submit')!=1) {
var iemessage = document.createElement("div");
$(iemessage).addClass("ie-message");
$('body').append(iemessage);
var frame = document.createElement("iframe");
$(frame).addClass("nsframe");
$(iemessage).append(frame);
var alerterror = document.createElement("div");
$(alerterror).addClass("alert error");
$(iemessage).append(alerterror);
var close = document.createElement("div");
$(close).addClass("close-text");
$(alerterror).append(close);
var textclose = document.createElement("div");
$(textclose).addClass("text-img");
$(textclose).text("close");
$(close).append(textclose);
var h2 = document.createElement("h2");
$(h2).text("Sorry, your web-browser is outdated...");
$(alerterror).append(h2);
var h3 = document.createElement("h3");
$(h3).text("Our site could be displayed not correctly in your browser.");
$(alerterror).append(h3);
var p = document.createElement("p");
$(p).text("We recommend you install new version of web-browser:");
$(alerterror).append(p);
var browserslist = document.createElement("div");
$(browserslist).addClass("browsers-list");
$(iemessage).append(browserslist);
var achrome = document.createElement("a");
$(achrome).attr("href", "http://www.google.com/chrome");
$(browserslist).append(achrome);
var spanchrome = document.createElement("span");
$(spanchrome).addClass("browser-button chrome");
$(spanchrome).text("Google Chrome");
$(achrome).append(spanchrome);
var afirefox = document.createElement("a");
$(afirefox).attr("href", "http://www.mozilla.com/firefox/");
$(browserslist).append(afirefox);
var spanfirefox = document.createElement("span");
$(spanfirefox).addClass("browser-button firefox");
$(spanfirefox).text("Mozilla Firefox");
//$(afirefox).append(spanfirefox);
var aopera = document.createElement("a");
$(aopera).attr("href", "http://www.opera.com/download/");
$(browserslist).append(aopera);
var spanopera = document.createElement("span");
$(spanopera).addClass("browser-button opera");
$(spanopera).text("Opera");
//$(aopera).append(spanopera);
var asafari = document.createElement("a");
$(asafari).attr("href", "http://www.apple.com/safari/download/");
$(browserslist).append(asafari);
var spansafari = document.createElement("span");
$(spansafari).addClass("browser-button safari");
$(spansafari).text("Apple Safari");
$(asafari).append(spansafari);
var aexplorer = document.createElement("a");
$(aexplorer).attr("href", "http://www.microsoft.com/windows/Internet-explorer/default.aspx");
$(browserslist).append(aexplorer);
var spanexplorer = document.createElement("span");
$(spanexplorer).addClass("browser-button ie");
$(spanexplorer).text("Internet Explorer");
$(aexplorer).append(spanexplorer);
$(iemessage).toggle();
$('.close-text').mouseover(function() {
$('.close-text').css({"border-bottom":"1px solid #000"});
$('.close-text').css({"color":"#959595"});
$('.close-text').css({"background":"url(/assets/browsers/button-close-hover.png) 100% 100% no-repeat"});
});
$('.close-text').mouseleave(function() {
$('.close-text').css({"border-bottom":"none"});
$('.close-text').css({"color":"#4e4e4e"});
$('.close-text').css({"background":"url(/assets/browsers/button-close.png) 100% 100% no-repeat"});
});
$('.close-text').click(function() {
$('.ie-message').hide();
createCookie('already_submit', 1, 0);
});
}
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
});
How can I random elements order (link), so that they appear every case.
As you see I need to random this lines:
$(afirefox).append(spanfirefox);
$(aopera).append(spanopera);
and so other. How can I do this, using my code style?
Function to shuffle an array in place:
function shuffle(array) {
var i = array.length;
if(i > 1)
while(--i) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
Add your afirefox, aopera and so on to an array:
var links = [afirefox, ..., aopera];
Append the shuffled list:
var $browserslist = $(browserslist);
$browserslist.append.apply(browserslist, shuffle(links));
EDIT: I removed my bad solution and instead suggest Fisher-Yates. See this interesting post on the matter - it seems to be exactly the same thing which you are doing.
Related
This code below is a javascript code to change texts and background properties from the body tag at the same time when the browser is clicked. I've just followed rules in w3school.com, actually, I'm doing the same as the examples do, but mine won't work and I've failed to find my fault. plz, help me.
var helloDiv = document.createElement("div");
var helloText = document.createTextNode("hi.");
helloDiv.appendChild(helloText);
var bodyntext = document.getElementsByTagName("body").appendChild(helloDiv);
var complementary = new Array();
var j = 0;
window.onclick = function(){
var background_color;
var body = document.getElementsByTagName("body")[0];
// var color = new Array();
var result = null;
var number = Math.round(Math.random()*0xFFFFFF);
for(var i = 0; i > 3; i++)
{
complementary[i] = (255-(number.slice(j,j+1).toString(10))).toString(16);
j = j + 2;
}
var clnumber = (complementary[0]+complementary[1]+complementary[2]).toString(16);
body.style.backgroundColor = "#"+ number.toString();
bodyntext.style.color = "#"+ clnumber.toString();
}
Here's your problem
var bodyntext = document.getElementsByTagName("body").appendChild(helloDiv);
Please note that the javascript functions that have plural names often return arrays which is the case here
document.getElementsByTagName("body") returns an array and you are trying to perform an invalid action, that is append child, to this array. You need to access an element using index and then perform this action.
so using
var bodyntext = document.getElementsByTagName("body")[0].appendChild(helloDiv); should fix your problem.
Use document.getElementsByTagName("body")[0] to achieve expected result, as getElementsByTagName() method returns a collection of all elements in the document with the specified tag name, as a NodeList object.
var helloDiv = document.createElement("div");
var helloText = document.createTextNode("hi.");
helloDiv.appendChild(helloText);
var bodyntext = document.getElementsByTagName("body")[0].appendChild(helloDiv);
var complementary = new Array();
var j = 0;
window.onclick = function(){
var background_color;
var body = document.getElementsByTagName("body")[0];
// var color = new Array();
var result = null;
var number = Math.round(Math.random()*0xFFFFFF);
for(var i = 0; i > 3; i++)
{
complementary[i] = (255-(number.slice(j,j+1).toString(10))).toString(16);
j = j + 2;
}
var clnumber = (complementary[0]+complementary[1]+complementary[2]).toString(16);
body.style.backgroundColor = "#"+ number.toString();
bodyntext.style.color = "#"+ clnumber.toString();
}
codepen - https://codepen.io/nagasai/pen/NLBXJE
Please refer this link for more details - https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName
I just change appendChild to document.body.appendChild(helloDiv) and added ID attribute for that div:
var helloDiv = document.createElement("div");
helloDiv.id = "myDIV";
document.body.appendChild(helloDiv);
var helloText = document.createTextNode("Click me");
helloDiv.appendChild(helloText);
var complementary = new Array();
var j = 0;
window.onclick = function(){
var background_color;
var body = document.getElementsByTagName("body")[0];
var helloText = document.getElementById("myDIV");
// var color = new Array();
var result = null;
var number = Math.round(Math.random()*0xFFFFFF);
for(var i = 0; i > 3; i++)
{
complementary[i] = (255-(number.slice(j,j+1).toString(10))).toString(16);
j = j + 2;
}
var clnumber = (complementary[6]+complementary[1]+complementary[2]).toString(16);
var clnumber2 = (complementary[0]+complementary[2]+complementary[6]).toString(11);
body.style.backgroundColor = "#"+ number.toString();
helloText.style.color = "#"+number.toString();
}
I'm trying to write a javascript bookmark that, based on the current URL, navigates you to another page. Then after that navigation is done, it looks for a particular ID tag then navigates you again.
I have the first navigation done and working:
javascript:
(function() {
ADCURL = "PageA.aspx";
var temp = window.location.href;
var tarr = temp.split("/");
var serv = "https://" + tarr[2];
var x = document.getElementsByTagName("html")[0].dir;
if (x) {
var x = document.getElementsByTagName("link");
for (i = 0; i < x.length; i++) {
var y = x[i].attributes[2].value;
var lookingfor = "_vti_bin";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(y)) {
var z = y.replace("_vti_bin/spsdisco.aspx", ADCURL);
var link = serv + z;
window.location.href = link;
}
}
} else {
DL5 = document.links;
for (lKi = 0; lKi < DL5.length; lKi++) {
map = DL5[lKi];
var lookingfor = "sites";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var lookingfor = "_layout";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {} else {
var lookingfor = "SharedDocuments";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var n = String(map).indexOf("SharedDocuments");
var x = String(map).slice(0, n);
var link = x + ADCURL;
window.location.href = link;
}
}
}
}
}
})();
however when I try to use a SetTimeout to delay the script so I can grab the ID i need from the page I navigated to, nothing happens (for now I just have a window alert in there as a placeholder until I get the SetTimeout to work):
javascript:
(function() {
ADCURL = "PageA.aspx";
var temp = window.location.href;
var tarr = temp.split("/");
var serv = "https://" + tarr[2];
var x = document.getElementsByTagName("html")[0].dir;
if (x) {
var x = document.getElementsByTagName("link");
for (i = 0; i < x.length; i++) {
var y = x[i].attributes[2].value;
var lookingfor = "_vti_bin";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(y)) {
var z = y.replace("_vti_bin/spsdisco.aspx", ADCURL);
var link = serv + z;
window.location.href = link;
}
}
} else {
DL5 = document.links;
for (lKi = 0; lKi < DL5.length; lKi++) {
map = DL5[lKi];
var lookingfor = "sites";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var lookingfor = "_layout";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {} else {
var lookingfor = "SharedDocuments";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var n = String(map).indexOf("SharedDocuments");
var x = String(map).slice(0, n);
var link = x + ADCURL;
window.location.href = link;
}
}
}
}
}
setTimeout(function(){window.alert("yes");}, 2000);
})();
Any ideas what's going on? When using javascript in bookmarks is it not possible to do what I'm trying to do?
I'm having a bit of trouble stringing together something that would change the color of the background every time you refresh the page, but in a sequence. I'm savvy with a lot of basic HTML, but not too much with java/css. I'm trying to have my background change along with some pictures for a page I'm working on, and I've figured out a code for the pictures to change on refresh, but I'm extremely confused on getting similar results with the background. Here's the code I have for the pictures:
<script type="text/javascript">
function loadNextImage1() {
//get image object
var myImg = document.getElementById('ImageRefresh');
//declare image directory path and image array
var thePath = "http://";
var theImages = new Array();
theImages[0] = "url";
theImages[1] = "url";
theImages[2] = "url";
//get current cookie value
var currentIndex = parseInt(getCookie());
var imgPath = thePath + theImages[currentIndex];
myImg.src = imgPath;
//set next cookie index
currentIndex += 1;
if(currentIndex > (theImages.length - 1)) {
currentIndex = 0;
}
setCookie(currentIndex);
}
function setCookie(someint) {
var now = new Date();
var addDays = now.getDate() + 7
now.setDate(addDays); // cookie expires in 7 days
var theString = 'imgID=' + escape(someint) + ';expires=' + now.toUTCString();
document.cookie = theString;
}
function getCookie() {
var output = "0";
if(document.cookie.length > 0) {
var temp = unescape(document.cookie);
temp = temp.split(';');
for(var i = 0; i < temp.length; i++) {
if(temp[i].indexOf('imgID') != -1) {
temp = temp[i].split('=');
output = temp.pop();
break;
}
}
}
return output;
}
</script>
<body onload="loadNextImage1();">
<img id="ImageRefresh">
Is there something similar I can do to make the background change on refresh as well? I figured I could make the background just a picture of the color I want, but I can't apply the img id to the head. If this is something like super simple please forgive me, a lot of this stuff is like a foreign language to me.
EDIT: Here's my current coding with a background color changer that halts the sequence entirely.
<script type="text/javascript">
function loadNextImage1() {
//get image object
var myImg = document.getElementById('Sidebar1');
//declare image directory path and image array
var thePath = "http://";
var theImages = new Array();
theImages[0] = "URL";
theImages[1] = "URL";
theImages[2] = "URL";
//get current cookie value
var currentIndex = parseInt(getCookie());
var imgPath = thePath + theImages[currentIndex];
myImg.src = imgPath;
//set next cookie index
currentIndex += 1;
if(currentIndex > (theImages.length - 1)) {
currentIndex = 0;
}
setCookie(currentIndex);
}
function setCookie(someint) {
var now = new Date();
var addDays = now.getDate() + 7
now.setDate(addDays); // cookie expires in 7 days
var theString = 'imgID=' + escape(someint) + ';expires=' + now.toUTCString();
document.cookie = theString;
}
function getCookie() {
var output = "0";
if(document.cookie.length > 0) {
var temp = unescape(document.cookie);
temp = temp.split(';');
for(var i = 0; i < temp.length; i++) {
if(temp[i].indexOf('imgID') != -1) {
temp = temp[i].split('=');
output = temp.pop();
break;
}
}
}
return output;
}
</script>
<script type="text/javascript">
function loadNextImage2() {
//get image object
var myImg = document.getElementById('Sidebar2');
//declare image directory path and image array
var thePath = "https://";
var theImages = new Array();
theImages[0] = "URL";
theImages[1] = "URL";
theImages[2] = "URL";
//get current cookie value
var currentIndex = parseInt(getCookie());
var imgPath = thePath + theImages[currentIndex];
myImg.src = imgPath;
//set next cookie index
currentIndex += 1;
if(currentIndex > (theImages.length - 1)) {
currentIndex = 0;
}
setCookie(currentIndex);
}
function setCookie(someint) {
var now = new Date();
var addDays = now.getDate() + 7
now.setDate(addDays); // cookie expires in 7 days
var theString = 'imgID=' + escape(someint) + ';expires=' + now.toUTCString();
document.cookie = theString;
}
function getCookie() {
var output = "0";
if(document.cookie.length > 0) {
var temp = unescape(document.cookie);
temp = temp.split(';');
for(var i = 0; i < temp.length; i++) {
if(temp[i].indexOf('imgID') != -1) {
temp = temp[i].split('=');
output = temp.pop();
break;
}
}
}
return output;
}
</script>
<script type="text/javascript">
function changeColor() {
//declare image directory path and image array
var colors = ["#00ffff", "#ff00ff", "ffff00"];
colors[0] = "#00ffff";
colors[1] = "#ff00ff";
colors[2] = "#ffff00";
//get current cookie value
var currentIndex = parseInt(getCookie());
var background = colors[currentIndex];
document.body.style.backgroundColor = background;
//set next cookie index
currentIndex += 1;
currentIndex %= colors.length;
setCookie(currentIndex);
}
function setCookie(someint) {
var now = new Date();
var addDays = now.getDate() + 7
now.setDate(addDays); // cookie expires in 7 days
var theString = 'imgID=' + escape(someint) + ';expires=' + now.toUTCString();
document.cookie = theString;
}
function getCookie() {
var output = "0";
if(document.cookie.length > 0) {
var temp = unescape(document.cookie);
temp = temp.split(';');
for(var i = 0; i < temp.length; i++) {
if(temp[i].indexOf('imgID') != -1) {
temp = temp[i].split('=');
output = temp.pop();
break;
}
}
}
return output;
}
</script>
<body onload="loadNextImage1(); loadNextImage2(); changeColor();">
The same script working with backgroundColor now:
<script type="text/javascript">
function loadNextImage1() {
//declare image directory path and image array
var colors = ["#eee", "#123123", "red"];
colors[0] = "#eee";
colors[1] = "#123";
colors[2] = "red";
//get current cookie value
var currentIndex = parseInt(getCookie());
var background = colors[currentIndex];
document.body.style.backgroundColor = background;
//set next cookie index
currentIndex += 1;
currentIndex %= colors.length;
setCookie(currentIndex);
}
function setCookie(someint) {
var now = new Date();
var addDays = now.getDate() + 7
now.setDate(addDays); // cookie expires in 7 days
var theString = 'imgID=' + escape(someint) + ';expires=' + now.toUTCString();
document.cookie = theString;
}
function getCookie() {
var output = "0";
if(document.cookie.length > 0) {
var temp = unescape(document.cookie);
temp = temp.split(';');
for(var i = 0; i < temp.length; i++) {
if(temp[i].indexOf('imgID') != -1) {
temp = temp[i].split('=');
output = temp.pop();
break;
}
}
}
return output;
}
</script>
<body onload="loadNextImage1();">
<img id="ImageRefresh">
You can use the HTML5 localStorage (or use sessionStorage if you want to keep the session) to save the index:
<script type="text/javascript">
function loadNextImage1()
{
//get image object
var myImg = document.getElementById('ImageRefresh');
//declare image directory path and image array
var thePath = "http://";
var theImages = new Array();
theImages[0] = "url";
theImages[1] = "url";
theImages[2] = "url";
// Remember to JSON parse it later
var local = localStorage.getItem('backgroundImageIndex');
// If local is null, then no localStorage (i.e. first load)
var currentIndex = (local === null) ? 0 : JSON.parse(local);
// Reset to 0 if bigger than 2
currentIndex = (currentIndex > 2) ? 0 : currentIndex;
// Set src
myImg.src = thePath + theImages[currentIndex];
// Write to localStorage
localStorage.setItem('backgroundImageIndex', JSON.stringify(currentIndex));
}
</script>
<body onload="loadNextImage1();>
<img id="ImageRefresh">
I have a javascript code with functions:
function convertTime()
function loadZive()
Let's say that I have the following code:
function convertTime(){
alert(exampleVariable);
};
function loadZive(){
var exampleVariable = 3;
convertTime();
};
It looks like my convertTime() function can't access exampleVariable. Is there any workaround?
Here is whole code:
function convertTime(publishedDate){
alert(publishedDate);
var date = publishedDate;
var publishedDay = date.toLocaleDateString();
var publishedHour = date.getHours(); //nemozno pouzit toLocaleTimeString (cielovy format ma byt bez sekund)
if (publishedHour < 10){
publishedHour = "0" + publishedHour;
};
var publishedMinute = date.getMinutes(); //nacitanie hodin a minut
if (publishedMinute < 10){
publishedMinute = "0" + publishedMinute;
};
var publishedTime = publishedHour +":"+ publishedMinute; //ich nasledne spojenie do casoveho formatu HH:MM
var publishedDateConverted = publishedDay +", "+ publishedTime;
};
function loadZive(publishedDateConverted){
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://www.zive.sk/rss/sc-47/default.aspx");
feed.setNumEntries(window.localStorage.getItem("entriesNumber"));
feed.load(function(result) {
if (!result.error) {
var feedlist = document.getElementById("feedZive");
for (var i = 0; i < result.feed.entries.length; i++) {
var li = document.createElement("li");
var entry = result.feed.entries[i];
var A = document.createElement("A");
var descriptionSettings = window.localStorage.getItem("descriptionSettings");
if (descriptionSettings=="true"){
var h3 = document.createElement("h3");
var p = document.createElement("p");
var pDate = document.createElement("p");
pDate.setAttribute("class","ui-li-aside");
var publishedDate = new Date(entry.publishedDate);
convertTime();
pDate.appendChild(document.createTextNode(publishedDateConverted));
h3.appendChild(document.createTextNode(entry.title));
p.appendChild(document.createTextNode(entry.content));
A.setAttribute("href",entry.link);
A.appendChild(h3);
A.appendChild(p);
A.appendChild(pDate);
}
else{
A.setAttribute("href",entry.link);
A.appendChild(document.createTextNode(entry.title));
};
li.appendChild(A);
feedlist.appendChild(li);
}
$("#feedZive").listview("refresh");
}
});
}
google.setOnLoadCallback(initialize);
};
Alert result is Undefined.
PS: exampleVariable isn't defined by the user; it is loaded from a feed, so I cannot define it before the convertTime() function.
As Danny said, or you can also pass variables this way:
function convertTime(exampleVariable){
alert(exampleVariable);
};
function loadZive(){
var exampleVariable = 3;
convertTime(exampleVariable);
};
Remove var from loadZive(), this makes the variable local to loadZive() only.
Alternatively, pass exampleVariable as a parameter to convertTime().
I'm new here and I'm also not much of a programmer but I hope you guys could help me with Javascript.
You see, I have this 3rd-party script that enables bloggers blogging on Blogger to add some kind of a list of related posts on their pages. Here is the script:
<script type='text/javascript'>
//<![CDATA[
// takes a json feed and creates an HTML-formatted list of the elements
function RelatedPostEntries(json) {
// change the next three variables as required
var homeUrl = 'http://whatever.blogspot.com/';
var maxNumberOfPostsPerLabel = 7;
var TargetElement = 'relatedcontent-list';
var ul = document.createElement('ul');
var maxPosts = (json.feed.entry.length <= maxNumberOfPostsPerLabel) ? json.feed.entry.length : maxNumberOfPostsPerLabel;
for (var i=0; i<maxPosts; i++) {
var entry = json.feed.entry[i];
var alturl;
for (var k=0; k<entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
alturl = entry.link[k].href;
break;
}
}
var li = document.createElement('li');
var a = document.createElement('a');
a.href = alturl;
if(a.href!=location.href) {
var txt = document.createTextNode(entry.title.$t);
a.appendChild(txt);
li.appendChild(a);
ul.appendChild(li);
}
}
for (var l=0; l<json.feed.link.length; l++) {
if (json.feed.link[l].rel == 'alternate') {
var raw = json.feed.link[l].href;
var label = raw.substr(homeUrl.length+13) + ':';
var txt = document.createTextNode(label);
var h = document.createElement('b');
var div = document.createElement('div');
div.appendChild(h);
div.appendChild(ul);
document.getElementById(TargetElement).appendChild(div);
}
}
}
function CodeHook(url, label, callback) {
var script = document.createElement('script');
script.setAttribute('src', url + 'feeds/posts/default/-/' + label + '?alt=json-in-script&callback=' + callback);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
}
//]]>
</script>
The script works fine but the problem is the original programmer has forgotten to add rel='bookmark' to his codings thus leaving us bloggers with a huge headache when it comes to SEO.
Can you guys show me where and how to add that rel attribute?
Thanks.
Try putting a.rel = 'bookmark' after when the element is declared, around here:
...
var li = document.createElement('li');
var a = document.createElement('a');
a.href = alturl;
a.rel = 'bookmark';
...
I think this will work.
var a = document.createElement('a');
a.href = alturl;
a.rel = "bookmark";