I'm trying to make a link, when user clicks it to change URL randomly to one of the vars.
$(".link").click(function(){
var safeLangs = ['en','al','de','fr','gr'];
var rand = function() {
return Math.floor(Math.random()*6);
};
var randomLangFunction = function() {
var randomLang = safeLangs[rand()];
return randomLang;
};
url = "?lang=" + randomLang();
window.location = url;
})
Problem is fixed by, thanks.
By Scott Marcus
At the end of your code, you incorrectly call your function: randomLang(); when it is really: randomLangFunction(). I also removed your rand function and incorporated it into the other.
$(".link").click(function(){
var safeLangs = ['en','al','de','fr','gr'];
var randomLangFunction = function() {
// No need to make a separate function for the random since
// this function is part of that process. Also, don't hard
// code "6" as the random multiplier as that will need to
// change if you add more languages. Just get the length
// of the languages array:
return safeLangs[Math.floor(Math.random()*safeLangs.length)];
};
url = "?lang=" + randomLangFunction();
console.log(url);
// Commented only for example to work:
// window.location = url;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="link" href="#">Click Me</a>
Related
my goal is to display a loading curtain when a query to Quick-Base takes too long.
I have the following code that I thought it was going to work but it somehow does not. Everything works except for the loading curtain because it is never executed when it should be.
My code:
<script>
window.onload = function(){
// .. more code here not related ...
function selectedValueChanged() {
$('#curtain').show();
var e = document.getElementById("record_id_select");
var value_selected = e.value;
var CO_picked_record_id = parseInt(value_selected);
var query_CO_line_details = "{'"+related_CO_fid+"'.EX.'"+CO_picked_record_id+"'}";
var records = getRecords(table_CO_line_details_DBID,query_CO_line_details);
var data_array = createArrayFromRecordsDrilled(records,CO_detail_record_categories);
var table_div = tableCreate(data_array,'table_container_1',"Please Enter Quantities",headerList);
$('#table_container_1').replaceWith(table_div);
$('#curtain').hide();
}
}
</script>
<div id='curtain' style='position:absolute;top:0;left:0;margin:0;background:rgba(255,255,255,.3); display:none; width:100%;height:100%;'><img id ="loading_text" src="loader.gif"></div>
</body>
The code works but the curtain is never shown even if the query takes a couple of seconds (as much as 6 seconds). If I comment out the line "$('#curtain').hide();" I can see the loading curtain working as expected but only after the query has finished. It is as if the function is not been executed line by line but it waits first to complete the query and then to show the curtain. I'm sure I'm missing something but I don't know what. Thank you.
use this instead(no need to add any HTML to page) :
function showLoading() {
if (document.getElementById("loadingDiv"))
return;
var div = document.createElement("div");
var img = document.createElement("img");
var span = document.createElement("span");
span.appendChild(document.createTextNode("Loading ..."));
span.style.cssText = "margin-top:50vh;font-family:IranSans;direction:rtl;color:#f78d24;"
img.src = "/images/LoadingImage.png";
img.style.cssText = "display:block;margin:auto;margin-top:calc(50vh - 64px);width:128px;height:128px;"
div.style.cssText = "position:fixed;width:100vw;height:100vh;background-color:rgba(0,0,0,0.85);top:0px;left:0px;z-index:10000;text-align:center";
div.id = "loadingDiv";
div.appendChild(img);
div.appendChild(span);
document.body.appendChild(div);
}
function hideLoading() {
var div = getElementById("loadingDiv");
if (div)
document.body.removeChild(div);
}
The solution as #keith suggested was to "transform" the getRecords function from synchronous to asynchronous.
I ended up making the whole function selectedValueChanged() "asynchronous" by using the setTimeout trick.
One solution that worked for me was the following:
function selectedValueChanged() {
var e = document.getElementById("record_id_select");
var value_selected = e.value;
var CO_picked_record_id = parseInt(value_selected);
var query_CO_line_details = "{'"+related_CO_fid+"'.EX.'"+CO_picked_record_id+"'}";
var records = getRecords(table_CO_line_details_DBID,query_CO_line_details);
var data_array = createArrayFromRecordsDrilled(records,CO_detail_record_categories);
var table_div = tableCreate(data_array,'table_container_1',"Please Enter Quantities",headerList);
$('#table_container_1').replaceWith(table_div);
}
}
function loadingSelectedValueChanged(callbackFunct){
setTimeout(function(){
callbackFunct()
$('#curtain').hide();
},10);
}
function selectedValueChangedUP() {
$('#curtain').show();
loadingSelectedValueChanged(selectedValueChanged);
}
And now instead of calling selectedValueChanged, I call selectedValueChangedUP.
What SetTimeout does is to execute the function that receives as parameter after a given amount of time. This process is done in an "asynchronous" way.
I have a series of pages named "page-1" "page-2" "page-3" ..."page-99". Is there a way to make a navigation so that whenever I click the "next" button it goes to the next page, and if I click "previous" it will go to the previous page depending on what the current page number is. I was wondering if there is a javascript solution to this since I have never used PHP.
next <!--it will go to page-3-->
previous <!--it will go to page-1-->
This should get you started (starting with your original code).
$('a[class^=page]').click(function(e){
e.preventDefault();
var num = this.className.split('-')[1]; //2
var nav = $(this).attr('data-nav');
if (nav == 'next'){
num = parseInt(num)+1;
//window.location.href = "page-"+num+'.html';
}else{
num--;
//window.location.href = "page-"+num+'.html';
}
alert('Navigating to: [ page-' +num+ '.html ]');
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
next <!--it will go to page-3-->
previous <!--it will go to page-1-->
Of course, this would be easier:
$('a[class^=page]').click(function(e){
e.preventDefault();
var num = this.className.split('-')[1]; //2
//window.location.href = "page-"+num+'.html'; //The "real" code
alert('Navigating to: [ page-' +num+ '.html ]'); //For demo purposes only
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" class="page-1" >next</a> <!--it will go to page-3-->
<a href="#" class="page-3" >previous</a> <!--it will go to page-1-->
And this would be easiest (using the file name):
//className *starts with* nav-
$('[class^=nav-]').click(function(e){
e.preventDefault();
var fileName = location.pathname.split("/").slice(-1);
var fileName = 'http://page-2.html'; //FOR DEMO ONLY
//alert(fileName); //should respond page2.html
var num = fileName.split('-')[1]; //2
var nav = this.className.split('-')[1]; //next
if (nav == 'next'){
num = parseInt(num)+1;
//window.location.href = "page-"+num+'.html';
}else{
num = parseInt(num)-1;
//window.location.href = "page-"+num+'.html';
}
alert('Navigating to: [ page-' +num+ '.html ]'); //For demo purposes only
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" class="nav-next" >next</a> <!--it will go to page-3-->
<a href="#" class="nav-prev" >previous</a> <!--it will go to page-1-->
You can do this with PHP or JS. But in either case you first need to be able to programmatically determine the page number of the currently displayed page.
You mention PHP, is this WordPress or some other similar CMS?
Okay so you mentioned that this is a basic website, but we still need to be able to pull that currentPageID. We could do this a few ways, the coolest would probably be to take it from the url, so let's do that.
To get the number from the url structure you mention in comments (hostname.com/page-1.html):
// Let's first grab the url and pull just the last segment, in case there are numbers anywhere else in the url.
var url = window.location.href;
var array = url.split('/');
var lastSegmentOfUrl = array[array.length-1];
// Next, let's regex that last segment for the first number or group of numbers
var reg = /\d+/;
var currentPageID = lastSegmentOfUrl.match(r); // That's it!
// Then some basic math to get the next and previous page numbers
var previousPageID = currentPageID - 1;
var nextPageID = currentPageID + 1;
// And finally we change the href values on the next and previous <a> elements
document.getElementById('previous').href('/page-' + previousPageID + '.html');
document.getElementById('next').href('/page-' + nextPageID + '.html');
This will keep working forever assuming your url structure stays the same insofar as the last segment only has the current page number and no other numbers, and also that the next and previous anchor tags ID's don't change.
Here is a method using location.pathname and String.prototype.replace, no extra templating required!
Update Includes check that page exists before fetching.
// Check that a resource exists at url; if so, execute callback
function checkResource(url, callback){
var check = new XMLHttpRequest();
check.addEventListener("load", function(e){
if (check.status===200) callback();
});
check.open("HEAD",url);
check.send();
}
// Get next or previous path
function makePath(sign){
// location.pathname gets/sets the browser's current page
return location.pathname.replace(
// Regular expression to extract page number
/(\/page\-)(\d+)/,
function(match, base, num) {
// Function to increment/decrement the page number
return base + (parseInt(num)+sign);
}
);
}
function navigate(path){ location.pathname = path; }
var nextPath = makePath(1), prevPath = makePath(-1);
checkResource(nextPath, function(){
// If resource exists at nextPath, add the click listener
document.getElementById('next')
.addEventListener('click', navigate.bind(null, nextPath));
});
checkResource(prevPath, function(){
// If resource exists at prevPath, add the click listener
document.getElementById('prev')
.addEventListener('click', navigate.bind(null, prevPath));
});
Note that this will increment the "page-n" portion of the path, even if you are in a sub-path. It will also work for non-html extensions.
E.g.,:
mysite.com/page-100/resource => mysite.com/page-101/resource
or
mysite.com/page-100.php => mysite.com/page-101.php
Please be advised that the following codes are generated by an engineer. (I don't have contact with the engineer right now)
Now here is the scenario. According to the engineer who had created this the whole collection of these scripts should be able to generate a button once edited properly and embedded to our website.
Before I implement this on our own website I want to test these codes to a simple page created through saving codes from our website. I ask the engineer if it is possible and he said yes.
Now here is the code that should be able to generate the button.
clickCall.js
(function () {
var createScriptElement = function (src, onload, onerror) {
var element = document.createElement("script");
element.type = "text\/javascript";
element.src = src;
element.onload = onload;
element.onerror = onerror;
return element;
};
var createLinkElement = function (src) {
var element = document.createElement('link');
element.href = src;
element.rel = 'Stylesheet';
element.media_type = 'text/css';
return element;
};
var createUI = function () {
var clickCallDiv = document.createElement('div');
clickCallDiv.style.cssText = 'width: 300px;height: 60px;position: fixed;z-index: 999;right: 20px;bottom: 320px;';
var call_btn = document.createElement("button");
call_btn.id = "dial_btn_call";
var session_div = document.createElement("div");
session_div.id = 'sessions';
var webcam_div = document.createElement("div");
webcam_div.style.cssText = 'height:0';
webcam_div.id = 'webcam';
var video_remote = document.createElement('video');
video_remote.id = 'remoteView';
video_remote.autoplay = 'autoplay';
video_remote.hidden = 'hidden';
var video_local = document.createElement('video');
video_local.autoplay = 'autoplay';
video_local.hidden = 'hidden';
video_local.muted = 'muted';
video_local.id = 'selfView';
webcam_div.appendChild(video_remote);
webcam_div.appendChild(video_local);
clickCallDiv.appendChild(call_btn); //add the text node to the newly created div.
var contain = document.createElement('div');
contain.appendChild(session_div);
contain.appendChild(webcam_div);
clickCallDiv.appendChild(contain);
return clickCallDiv;
};
var urls = {};
urls.rtcninja = 'rtcninja.js';
urls.jquery = 'jquery.js';
urls.i18n = "jquery.i18n.js";
urls.messagestore = "jquery.i18n.messagestore.js";
urls.jssip = 'jssip.js';
urls.init = 'init.js';
urls.gui = 'gui.js';
urls.css = 'style.css';
var rtcninja_script = createScriptElement(urls.rtcninja, function () {
// Must first init the library
rtcninja();
// Then check.
if (!rtcninja.hasWebRTC()) {
console.log('WebRTC is not supported in your browser :(');
} else {
document.body.appendChild(createUI());
}
});
var jquery_script = createScriptElement(urls.jquery, function(){
document.head.appendChild(i18_script);
document.head.appendChild(jssip_script);
document.head.appendChild(gui_script);
document.head.appendChild(init_script);
});
var i18_script = createScriptElement(urls.i18n, function(){
document.head.appendChild(messagestore_script);
});
var messagestore_script = createScriptElement(urls.messagestore);
var jssip_script = createScriptElement(urls.jssip);
var init_script = createScriptElement(urls.init);
var gui_script = createScriptElement(urls.gui);
var click_call_css = createLinkElement(urls.css);
document.head.appendChild(jquery_script);
document.head.appendChild(rtcninja_script);
document.head.appendChild(click_call_css);
})();
That script, when embedded, should be able to generate a button. The way he embedded the script on their website is through this
<script>
document.write('<script src="sourcefile/clickCall.js">/script>')
</script>
But this won't work on my side so I tried this
document.write('<sc' + 'ript src="clickCall.js">/sc' + 'ript>')
Now my first problem is that this script prevents all other scripts from loading, causing to have an empty output. another is that it won't display the expected button that it was suppose to show on the webpage. My solution to this problems was to implement DOM but I don't know how I'll implement it especially because I can't understand how it works and how to implement it. Could you kindly explain to me how DOM works and how am I going to implement it? Thanks
document.write when executed just writes the string and doesn't execute the inside script.
Hence, instead of this,
<script>
document.write('<script src="sourcefile/clickCall.js"></script>')
you can directly call your script.
<script src="sourcefile/clickCall.js"></script>
I enter to browser this link
https://google.com.vn;
Google redirect to https://www.google.com.vn;
I want alert full url redirect.
I used this code:
processNewURL: function(aURI) {
var tabIndex = gBrowser.tabContainer.selectedIndex;
var referredFromURI = gBrowser.tabContainer.childNodes[tabIndex].linkedBrowser.webNavigation.referringURI.spec;
alert(referredFromURI);
},
But it always alert https://www.google.com.vn,
and I tested with some short link example bit.ly/R9j52J . It isn't ok.
Please help me.
this works, i also show 2 methods to get to webNavigation. the second method is just longed winded way to teach other stuff, recommended way is method 1.
var processNewURL = function(e) {
console.log('e:', e);
var win = e.originalTarget.defaultView;
//start - method 1 to get to webNav:
var webNav = win.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation);
var referredFromURI = webNav.referringURI;
//end - method 1
//start - method 2 long winded way:
/*
var domWin = win.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
var tab = domWin.gBrowser._getTabForContentWindow(win);
//console.log('tab:', tab);
var referredFromURI = tab.linkedBrowser.webNavigation.referringURI;
*/
//end - method 2
if (referredFromURI != null) {
win.alert('referred from:' + referredFromURI.spec);
} else {
win.alert('not redirected');
}
}
gBrowser.addEventListener('DOMContentLoaded', processNewURL, false);
I am a beginner of javascript and jquery and i have 11 image tags in html. I want to
basically change sources of these tags using js and jquery. This code is not working and I am not getting any errors in firebug, can some one please tell me where I am doing wrong?
var imagesArray2=["01.png","02.png","03.png","04.png","05.png","06.png","07.png","08.png","09.png","10.png","11.png"];
var elementArray2 = ["#img1","#img2","#img3","#img4","#img5","#img6","#img7","#img8","#img9","#img10","#img11"];
var imagesArray,elementArray;
var elementInArray;
document ready
$(function(){
setInterval(Myfunction(),1000);});
my function code which has a loop based on elementsInArray variable value and it calls imageFadeAnimations function
function Myfunction(){
if(elementsInArray === 0){
imagesArray = imagesArray2;
elementArray = elementArray2;
elementsInArray = elementArray.length;
var imageChanges = Math.floor(Math.random()*elementsInArray);
imageFadeAnimations(imageChanges);
}
else
{
elementsInArray=elementArray.length;
imageChanges = Math.floor(Math.random()*elementsInArray);
imageFadeAnimations(imageChanges);
}
}
takes an integer as argument
function imageFadeAnimations(imageChanges){
for(var k = 0;k<imageChanges;k++){
var element = Math.floor(Math.random()*elementsinArray);
var image=Math.floor(Math.random()*elementsinArray);
imageChanger(elementArray[element],imageArray[image]);
elementArray.splice(element,1);
imagesArray.splice(image,1);
}
}
function imageChanger(b1,b2){
$(b1).fadeOut(500,function(){
$(b1).attr("src",b2);
$(b1).fadeIn(500);
});
}
You are making heavy weather out of something that jQuery can make very simple.
First wrap your images in an element (typically a div or a span) with id="imageContainer".
Now, if I understand correctly, your code will simplify to :
$(function() {
var imagesArray = ["01.png", "02.png", "03.png", "04.png", "05.png", "06.png", "07.png", "08.png", "09.png", "10.png", "11.png"],
$images = $("img", "#imageContainer");
setInterval(function() {
$images.each(function() {
var $img = $(this),
i = Math.min(imagesArray.length-1, Math.floor(Math.random() * imagesArray.length));
$img.fadeOut().promise().then(function() {
$img.attr("src", imagesArray[i]).fadeIn(500);
});
});
}, 1000);
});
EDIT 1
As #mplungjan points out below ...
If the img nodes were initialised with src attributes, then imagesArray can be composed by grabbing the srcs from the DOM as follows (replacing two lines above) :
var $images = $("img", "#imageContainer"),
imagesArray = $images.map(function() { return this.src; }).get();
I believe this jquery/zepto code is not the smaller, but the easier to understand:
function changeImg(){
$("#img1").attr('src', '01.png');
$("#img2").attr('src', '02.png');
$("#img3").attr('src', '03.png');
$("#img4").attr('src', '04.png');
$("#img5").attr('src', '05.png');
$("#img6").attr('src', '06.png');
};