Random image function (javaScript) not displaying local image when prompted - javascript

So I've tried several things to fix this but nothing seems to work. it was working OKAY earlier but something happened and now I cant get it to display a random image from a JS array in the target div.
renamed all the image files so they had no spaces
edited document.getElementById("profPic").innerHTML = '<img src="'+imagesArray[num]+'">'; several times to no avail
Checked SO for solutions/work around but concluded it must be something to do with the file formatting that i am unaware of.
Tried putting displayImage(); in the div container. Also tried with document.write
var imagesArray = ["img/mascotImages/CCF2_(281).jpg", "img/mascotImages/CCF2_(282).jpg"];
function displayImage() {
var num = Math.floor(Math.random() * (imagesArray.length + 1));
document.getElementById("profPic").innerHTML = '<img src="' + imagesArray[num] + '">';
}
function myFunction(e) {
if ((e.target.id === 'mySearch' && e.keyCode === 13) || e.target.id === 'searchButton') {
e.preventDefault();
var searchValue = document.getElementById("mySearch").value;
for (var i = 0; i < users.length; i++) {
if (users[i]['last_name'] === searchValue) {
document.getElementById("usernameOut").innerHTML = (users[i].username);
document.getElementById("firstNameOut").innerHTML = (users[i].first_name);
displayImage();
return;
}
}
}
}
<div id="return">
<div id="profPic"></div>
<!--profPic-->
<div id="usernameOut"></div>
<!--usernameOut-->
<div id="firstNameOut"></div>
<!--firstNameOut-->
</div>
What is supposed to happen is that when the user searches something in a search box, data from another array is displayed in <div id="usernameOut"> and <div id="firstNameOut"> etc. I wanted a random picture to display also when the user clicked search/hit enter.
Is something wrong with the naming conventions of the files? are they in one too many folders? i'm sure this is something very simple, but it's had me staring at it for several hours.

Arrays indexes start with 0, not 1. Therefore, with only 2 images in your array, the max index should be 1. But your code Math.floor(Math.random() * (imagesArray.length+1)) can at times return 2.
Just get rid of the +1:
Math.floor(Math.random() * imagesArray.length)

Related

JavaScript Choose your own adventure game random number function in loop problem

I'm writing a choose your own adventure program where If a specific option is chosen (example to wait) the user gets a random number between 1-10 to do push ups(the push-ups would be the user clicking on the prompt "ok" button however many times the random number is equal to) here's my code so far but I keep getting errors. I'm a complete noob so go easy on me.
var count = Math.floor((Math.random() * 10) + 1);
var setsOf10 = false;
function pushUps() {
alert("Nice! Lets see you crank out " + pushUps + "!");
}
if (setsOf10 == pushUp) {
alert("Nice! Lets see you crank out " + pushUp + "!");
setsOf10 = true;
}
for (var i=0; i<count; i++){
pushUps();
}
else {
alert("Really, thats it? Try again");
}
while ( setsOf10 == false);
}
After playing with this some more I can tell i'm close but still don't have it. and again, I'M NOT ASKING YOU TO SOLVE THIS FOR ME JUST NEED POINTERS AS TO WHAT IM DOING WRONG OR MISSING. Here's what I have, Its giving me my random number I just need it to allow me to click the "ok" button however many times the random number has assigned me.
var pushUpSets = Math.floor((Math.random() * 10) + 1);
function pushUps(){
alert(pushUpSets);
if (pushUpSets < 3){
var weak = "Thats it? Weak sauce!";
alert(weak);
}
else{
alert("Sweet lets get some reps in!");
}
for (i=0; i>3; i++){
pushUps(pushUpSets);
}
}
Here, the make a choice button is just dummy to allow us to go to do push ups. Each click decrements our count.
// This is important, we use this event to wait and let the HTML (DOM) load
// before we go ahead and code.
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#choice').addEventListener('click', makeChoice);
});
function makeChoice() {
// Call a method to set random pushups and setup the click event
setUpPushUp();
// Here we change the display style of the push up section so that it shows to the player.
document.querySelector('.activity').style.display = 'block';
}
// The pushups variable is declared at the document level
// This way our setUpPushUp and doPushUp functions have easy access.
let pushUps = 0;
function setUpPushUp() {
// Create a random number of pushups, in sets of 10.
// We add an extra 1 so we can call the doPushUp method to initialize.
pushUps = (Math.floor((Math.random() * 10)+1)*10)+1 ;
// Add a click event to the push up button and call our doPushUp method on each click.
document.querySelector('#push').addEventListener('click', doPushUp);
// This is just an init call, it will use the extra 1 we added and place test in our P tag.
doPushUp();
}
function doPushUp() {
// Get a reference to our output element, we will put text to player here.
let result = document.querySelector('p');
// They have clicked, so remove a push up.
pushUps--;
// See if the player has done all the required push ups (i.e. pushUps is 0 or less.)
if (pushUps > 0) {
result.innerText = `You need to crank out ${pushUps} pushUps`;
} else {
result.innerText = 'Nice work!';
}
}
.activity {
display: none;
}
<button id="choice">Make a choice !</button>
<div class="activity">
<p></p>
<button id="push">Push</button>
</div>

Making a custom directive with a function

While working I come up with this problem, I made a dashboard on which user's image is loaded & if no image is provided by the user then a fallback image with his name initials is shown.
<img class="md-avatar" ng-src="{{item.image}}" ng-show="item.image"/>
<div ng-hide="item.image" class="avatar" ng-if="!item.image">{{vm.initials(item.name)}}</div>
vm.initials: function(fullName) {
var initials = [];
var k;
initials.push(fullName[0]);
for(var i=1 ; i<fullName.length ; i++){
if(fullName[i]==' '){
initials.push(fullName[i+1].toUpperCase());
}
}
if(initials.length == 1){
initials.push(fullName[1]);
}
k = initials[0].toUpperCase();
k+=initials[1];
return k;
}
This is working fine but the problem is I want to use this at multiple places so I have to add vm.initials function at every place. I've tried to make a directory in angular but failed, can anyone help in making a directory or any new approach.

Finding the image count in a web page

I have a JS code, that gets called in different web pages of my clients. I want to fetch the total number of images. I want only those images that are visible to the user and not just any other images. This is my JS code
function getImageCount(topWindow) {
try {
var images = topWindow.document.getElementsByTagName('img');
var imageCount;
for (var i=0, length = images.length; i < length; i++) {
var image = images[i];
var clientWidth = image.clientWidth;
if(clientWidth && clientWidth > 1) {
var src = image.getAttribute('src');
if(src) {
src = src.toLowerCase();
if(src.indexOf('.jpg') !== -1 ||
src.indexOf('.jpeg') !== -1 ||
src.indexOf('.gif') !== -1 ||
src.indexOf('png') !== -1) {
imageCount = imageCount ? ++imageCount : 1;
}
}
}
}
return imageCount;
} catch (e) {
processError("getImageCount", e);
}
}
var imageCount = getImageCount(top);
I have been trying a lot to stabilize this code so that it works correctly across all different types of web pages. Basically what I want is a generic code that captures image counts correctly.
Eg:
My code gives image count as 1 for http://www.msn.com/en-us/news/other/one-free-agent-every-nfl-team-should-sign-this-offseason/ss-AAmLlC0#image
What I want is a GENERIC CODE that gives me a correct image count irrespective of where it runs. Can some one give me some detailed solutions.
I would appreciate a lot.
To simplt count all the images (<img>) on the page:
document.images.length
And to count all the "visible" images (ones with width and height):
[...document.images].filter(img => img.clientWidth && img.clientHeight).length
This will give you the number of images on the page. This does not include CSS images. since your code didn't either then I take it you want <img> ones
I didn't quite understand the meaning of irrespective of where it runs.. can you elaborate?
// Extract images
websiteImages = document.getElementsByTagName('img');
for (url in websiteImages)
console.log(websiteImages.length);
//Extract inbound and outbound links
Links = document.querySelectorAll('a');
for (link in Links)
console.log(Links[link].href);
Paste this Scripts into your console of browser
Check on the Below Link/ any Link you like
(https://news.google.com/topstories?hl=en-IN&gl=IN&ceid=IN:en&gl=IN&ceid=IN:en)
The above-mentioned script will give all the Images present in the webpages.
And the second script will give all the number of Inbound and Outbound/exit links
Just apply Some filter as per your use case and you will be good to go.
Use this simple approach for links
$$('a').length
To count the number of images on a webpage use the below code:
$$('img').length

JQuery Gallery next button not working properly?

I am trying to create a basic gallery using JQuery.
The basic idea is that all image files are called x.png (where x is a number), and the program adds a number to the current number creating x+1.png and so on.
The code i have is:
function gal2(){
var amount = $(".imagelist > img").length;
var next = $("#display").attr('src').replace('.png', '');
if ($("#display").attr('src').replace('.png', '') >= amount) {
$("#display").attr('src', next+".png");
next++;
} else {
$("#display").attr('src', next+".png");
next++;
};
}
gal2 is called on a button press <input type="button" onclick="gal2()">,
.imagelist is a div containing the images,
#display is the main image being shown,
Example Website
The problem is that nothing happens except if one is selected than it will back to the original one every time.
P.S: It's for a year 9 secondary school project
You made some edits to your script and now it work fine : https://jsfiddle.net/IA7medd/qwmt7Lep/2/
function gal2(){
var amount = $(".imagelist > img").length;
var current = parseInt($("#display").attr('src').replace('.png', ''));
var next = current + 1;
if (current < amount) {
$("#display").attr('src', next+".png");
} else {
$("#display").attr('src', "1.png");
};
}

Creating a new line for an output using the same variable?

Very much a newbie here and wanting a bit of guidance.
I'm trying to create a project where you bind a key to start a timer then show an output in the results box. However i'm facing an issue where I need to create a new line if the user releases the bound button to start a new timer, however I can't find a way to start the timer again. Bear in mind within the time, a user could press the bound key over a hundred times, I don't want to manually create new lines and timer's.
My thoughts are creating a a random token, then on release, it creates a break, if the next line doesn't match this token it begins again.
Edit:So you can see, the value is based on the 2 variables, and even when I hold down the specific button again, it just adds to the current smallTime. I know this is how it's currently build, but i'm trying to get it to reset and go to the next line dynamically.
Any help would be greatly appreciated.
<html>
<head>
<textarea class="code_input" name="allInputs" id="textareaCode" wrap="logical" rows="10" cols="50" readonly="true"> </textarea>
<script type="text/javascript">
var shortSeconds = 0;
var shortmillisec = 0;
function buttonPressed(e) {
key = String.fromCharCode(e.keyCode).toLocaleLowerCase()
//alert (key)
keyInput = e.keyCode
if (withinTime == true && key == bind) {
shortDisplay()
shortTimerFunction();
}
}
function shortDisplay() {
if (shortmillisec >= 9) {
shortmillisec = 0
shortSeconds += 1
}
else
shortmillisec += 1
}
function startstoptimerShort() {
if (shortTimer > 0) {
clearTimeout(shortTimer);
shortTimer = 0;
} else {
withinTime = true
shortTimerFunction()
}
}
function shortTimerFunction() {
smallTime = shortSeconds + "." + shortmillisec;
shortTimer = setTimeout("shortTimerFunction()", 100);
//need to work out what line to put the output on
allInputs = document.getElementById('textareaCode')
allInputs.value = (textbox3.value) + (": " + smallTime) + '\n';
}
</script>
</body>
</html>

Categories