Replace Picture Source (Error Handling) - javascript

Hi I have a script wich changes the source of an image ie webpics/1.jpg to webpics/2.jpg on click of an image. One problem i am having though is that the script will still work for one more image after there is images, so if i have 11 images i can press next 11 times and will get an empty image, what i would like is for the script to run a error check and stay on the current image if the next on doesn't exist. Here is the script:
$("#prev, #next").click(function() {
var currentNumber = parseInt($("#image1").attr("src").split('gallery/')[1]); // get the
number
var newNumber = ($(this).attr("id")=="next")?currentNumber+1:currentNumber-1;
var testImage = new Image();
testImage.onload=function() {
var img = $("#image1");
img.attr("src",this.src);
img.css("visibility","visible");
}
testImage.onerror=function() {
$("#image1").css("visibility","hidden");
}
testImage.src="http://www.yogahealth.net.au/gallery/"+newNumber+".jpg";
return false;
});

Do you know how many images exist? If so, just test if the new number would exceed the total count (if newNumber ...) and do nothing (i.e. skip the part where you change the testImage.src.
For example, you need to have the total count in the variable totalImages, then you could do:
$("#prev, #next").click(function() {
var currentNumber = parseInt($("#image1").attr("src").split('gallery/')[1]); // get the number
var newNumber = ($(this).attr("id")=="next")?currentNumber+1:currentNumber-1;
var totalImages = // get the number of total images here
if ((newNumber > totalImages) || (newNumber <= 0)) {
return false; // just do nothing
}
// here comes the rest of your code
});
Note that I also added the possibility that your number becomes less than 0 or 0, depending on whether you have an image named 0. If yes, you can change the <= to <, otherwise it won't show the 0 image.
In order to get this number into your Javascript code, you could either render the code using PHP and insert it into your script with <?php echo $total; ?> or you extract it from another element from the HTML page, as you did with the currentNumber.

Related

How to write a java script for specific Test attempts

I am having a java scripts for a game, but this game is like a test and if the user failed the game he will retake the test (redo the game), but I want a specific number of attempts only for the user to re do the test. now what I have, makes the user start from the beginning without any limitations even if he re do it for like 100 times, he will keep go back to the beginning.
I need in the fail massage to give another attempt (form like max 4 attempts) if failed once then the next fail massage to give him 3 tries and then 2 and then last one, and then he can't redo the test.
Script 1;
var player=GetPlayer();
var textArray = [];
for (var i = 1; i <= 15; i++) {
textArray.push(i);
};
var itemsLeft = textArray.length;
textArray=textArray.map(String).toString();
player.SetVar("Text_Array", textArray);
player.SetVar("Items_Left", itemsLeft);
Script 2:
//get the StoryLine player
var player=GetPlayer();
//get Storyline variable value as a string
var textArray=player.GetVar("Text_Array");
//Convert string to a numeric array
numArray=textArray.split(",").map(Number);
//Get a random number from the array and send it to StoryLine
var randNum = numArray[Math.floor(Math.random() * numArray.length)];
player.SetVar("Random",randNum);
//Remove the random number from your array and get the array's length
numArray.splice(numArray.indexOf(randNum), 1);
var itemsLeft=numArray.length;
//Convert array to a string and send it back to SL along with the array's length
textArray=numArray.map(String).toString();
player.SetVar("Items_Left", itemsLeft);
player.SetVar("Text_Array", textArray);

Changing variable based on video time

I need to display a "caption" from a video but I cannot use built in captions provided by a vtt file for my situation. I created an array that stores the key,value pair (time, caption). I traverse that array every time the video time is updated and find which caption fits the current time. This solution works and I haven't had any issues (performance or otherwise) but it just feels like brute force to me, I'm hoping someone can help me either refine what I have or guide me toward a more elegant solution. Any comments or criticism is appreciated.
//this function is called whenever video time is updated
this.onUpdateTime = function(currentTime, totalTime) {
this.currentTime = currentTime;
this.totalTime = totalTime;
/*the for statement traverses the array chapters which contains
[{"time": X,"caption": "XYZ"},...]*/
for (var i = 0; i < $scope.chapters.length; i++) {
/* the first if statement checks if (i is not the same as
chapters.length (this was done to prevent an off by one error) and the time of
the video is greater than or equal to time at chapters[i] and the time of the
video is still less than time at the next chapter marker chapter[i+1]*/
if (i != $scope.chapters.length - 1 && currentTime >= $scope.chapters[i].time && currentTime < $scope.chapters[i + 1].time) {
/*set the caption to the value from chapters[i].caption*/
$rootScope.caption = $scope.chapters[i].caption;
/*I have never used $scope.$apply but it seemed to be needed to get the caption to display in my view*/
$scope.$apply(); {
/*break the for loop so that it does not needlessly loop through the rest of the array after finding a match*/
break;
}
/*this if statement if for when i is equal to chapters.length -1, it is the final value in the array so it does
not check against the "next value" like the previous if statement does because there is not next value*/
} else if (currentTime >= $scope.chapters[i].time && i == $scope.chapters.length - 1) {
/*set the caption to the value from chapters[i].caption*/
$rootScope.caption = $scope.chapters[i].caption;
/*I have never used $scope.$apply but it seemed to be needed to get the caption to display in my view*/
$scope.$apply(); {
/*break the for loop so that it does not needlessly loop through the rest of the array after finding a match*/
break;
}
/*if there is not chapter marker at the current time*/
} else {
/*set the caption to a blank value because no match was found therefore there is no caption*/
$rootScope.caption = "";
$scope.$apply();
}
}
// console.log("onUpdateTime function, currentTime is: " + currentTime);
// console.log("onUpdateTime function, totalTime is: " + totalTime);
};

jquery hide/show or condiiton failing

Is there anything wrong with the jQuery/JS below? I have an input field aAmt which on change calls below. ${dAmt} = "10000" from DB. It basically converts the number to $ format(eg.. 23 to $23.00) and focuses the value to the input field. Issue is the if loop (if(aAmt >= a_amount)...) fails.
Even if the condition fails it goes to if loops and shows the div which should not happen. I don't see any error in developers console.
$('#aAmt').change(function() {
var aAmt = $("#aAmt").val();
var a_amount = "${dAmt}";
curFormat(aAmt);
if(aAmt >= a_amount)
{
$("#dsDiv").show();
}else{
$("#dsDiv").hide();
}
});
function curFormat(aAmt)
{
var nAmt = Number(aAmt.replace(/[^0-9\.]+/g,""));
var fAmt = '$' + nAmt.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
document.getElementById("aAmt").value = fAmt;
}
Have you tried to convert a_amount to an int, to be sure to compare two integers together:
var a_amount = parseInt("${dAmt}");

Random URL redirect from array

/**
* Political Animals
* contentscript.js is loaded on each page(s) listed in manifest.json
* This plugin replaces all the images on the website of news sites with pictures of
* animals in suits, as a commentary on what the news has become. Made for Web 2
* November 20, 2013
*/
//Random Image array
var arrayImg = ['http://www.whattofix.com/images/PoliticalAnimal.jpg','http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals26.jpeg','http://img1.etsystatic.com/016/1/7647665/il_340x270.411173311_ojy5.jpg','http://ny-image0.etsy.com/il_fullxfull.85564656.jpg','http://afraidofmice.com/blog/wp-content/uploads/2011/08/berkleyill.jpg','http://elizabethmarshallgalleryblog.files.wordpress.com/2011/05/etsy-panda-for-blog1.jpg','http://moesewco.typepad.com/.a/6a00e5500684b488330120a5c7cf3a970c-300wi','http://ih3.redbubble.net/image.13276877.5059/flat,800x800,070,f.u1.jpg','http://www.tildeshop.com/blog/wp-content/uploads/2012/09/SeaLionFemale-21.jpg'];
//redirect
var acceptedWebsites =['www.cnn.com', 'www.nytimes.com', 'www.latimes.com', 'www.washingtonpost.com', 'www.nbcnews.com', 'www.foxnews.com'];
var currentUrl = document.location.href;
var referrer = currentUrl.match(/:\/\/(.[^/]+)/)[1];
//Making sure the code does what I want it to. As long as the link shows a number greater than -1, then the site extension is working
console.log(referrer);
console.log(acceptedWebsites.indexOf(referrer));
//var url = acceptedWebsites[Math.floor(Math.random()*acceptedWebsites.length)];
//document.location.href = url;
// image source goes through the following script function
$('img').each(function(){
// creating the randomizing
var random = arrayImg[Math.floor(Math.random()*arrayImg.length)];
//Takes the current array and applies the source with the random function
$(this).attr('src', random);
//removing the stretch
var theWidth = $(this).width();
var theHeight = $(this).height();
if (theWidth < theHeight) {
$(this).height(150);
}
else {
$(this).width(150);
}
});
//alert ("Go to any of the follow websites: fox.com, nbc.com, nytimes.com, latimes.com, or cnn.com");
I have this array in javascript. I want to have it so that the user is automatically redirected to one of the links from the array, possibly randomly. I don't know if I can do this in javascript. I am using this for a chrome extension, so I don't know if I can use php.
These are fantastic answers, except they constantly redirect. I want it so that they are just redirected to one from the array once, not constantly redirect.
**Edit 2: I added my whole code because something is causing there to be a constant redirect instead of only once.
**Edit 3: I updated my code. The console.log proves that my new variables work and do ==-1. How can I use them to redirect?
Get a random URL from the array, and redirect ?
if ( acceptedWebsites.indexOf(document.location.href) == -1 ) {
var url = acceptedWebsites[Math.floor(Math.random()*acceptedWebsites.length)];
document.location.href = url;
}
Try the following:
var acceptedWebsites =['http://www.cnn.com/', 'www.nytimes.com', 'www.latimes.com', 'http://www.washingtonpost.com/', 'http://www.nbcnews.com/', 'http://www.foxnews.com/'];
var number = Math.floor(Math.random() * acceptedWebsites.length);
number will generate a random number between 1 and the number of entries in your acceptedwebsites array.
window.location = acceptedWebsites[Math.floor(Math.random() * acceptedWebsites.length)];
The basic jist of the logic would be...
var acceptedWebsites = ['http://www.cnn.com/', 'www.nytimes.com', 'www.latimes.com', 'http://www.washingtonpost.com/', 'http://www.nbcnews.com/', 'http://www.foxnews.com/'];
var randomLink = Math.floor(Math.random() * acceptedWebsites.length);
window.location = acceptedWebsites[randomLink];
// Get random site
var randomSite = acceptedWebsites[Math.floor(Math.random() * acceptedWebsites.length)];
// redirect to selected site
window.location = randomSite;
Generate a "random" key and use window.location.href to redirect the user. Others have posted the same approach, though with less explanation. I'm giving my best to let you actually understand what happens here.
Note that most of this code is comments. It looks longer than it actually is.
var acceptedWebsites = ['http://www.cnn.com/', 'www.nytimes.com', 'www.latimes.com', 'http://www.washingtonpost.com/', 'http://www.nbcnews.com/', 'http://www.foxnews.com/'];
// This function returns a random key for an array
function randomKey(arr) {
// Math.random() returns a number between 0 and 0.99999...
// If you multiply this value with the length of an array, you get a
// random floating point number between 0 and that length.
// Use Math.floor() to round it down to the next integer
return Math.floor(Math.random() * arr.length);
}
// Select a random website from the array
var key = randomKey(acceptedWebsites);
var newLocation = acceptedWebsites[key];
// Redirect the user
window.location.href = newLocation;
Try this solution:
var size = acceptedWebsites.length;
var x = Math.floor((Math.random()* size)+1);
Now use loop for value x-1 like
var location = acceptedWebsites[x-1];
window.location.href = location;
If we run this in loop ,we will get different value of x every time between 0-size of array and then we can use that random value to randomly redirect.
window.location doesn't work since content scripts are unprivileged. Further more, window.location.href returns the current location, but it is not a method so you cannot overwrite it.
you'll need to:
Send redirect url from a content script to a background page:
var url = acceptedWebsites[Math.floor(Math.random()*acceptedWebsites.length)];
chrome.extension.sendRequest({redirect: url });
In a background page update tab's url which would cause redirect:
chrome.extension.onRequest.addListener(function(request, sender) {
chrome.tabs.update(sender.tab.id, {url: request.redirect});
});

winjs/javascript: input number validation?

I have textbox with id number. I have 454 html files and I displayed these files by the respective input number. if users gives 3 and it will displays /def/f3.html and 4 means it will displays /def/f4.html and likewise it will all 454 files.
If users gives other than these number, an alert box alerts user. Still now, there is no problem.
What i am asking is, if users gives 003 and it will try to display /def/f003.html. Since, i don't have files with that name. it shows error.
Any help regarding this issue, will be seriously much appreciated. JavaScript Code:
function buttonClick()
{
var getFile = document.getElementById("number").value;
if (getFile < 455 && getFile > 0) {
var output = new WinJS.UI.HtmlControl(document.getElementById("def-content"), { uri: '/def/f' + getFile + '.html' });
} else {
var popup = Windows.UI.Popups.MessageDialog("Expected Value Range: 1 to 454.");
popup.showAsync();
}
}
use var getFile = parseInt(document.getElementById("number").value) and you also have to make sure than no file name number starts with zero except for f0.html.

Categories