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");
};
}
Related
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>
I apologize I am new to javascript. I am trying to toggle a relay from a website using setInterval. The relay is a Sainsmart with 16 channels and it is connected to an arduino controlled by a raspberry pi. The goal is to eventually have three independent relays toggling at particular intervals. However, every attempt to get the first one working fails. In addition, every time I add a setInterval within a function or global, freezes the live streaming video from my ip camera. I am using a sandbox key through ably.
The html code and script work to toggle the relay on, and then a second button will toggle it off, but I need a single button to accomplish it.
The button initiates the sequence with a counter dictating whether the relay toggles on or off. It is set up to toggle on with an even number and off with an odd number. Any help would be greatly appreciated.
Here is the updated code I am trying to work with.
<div class="grid-item"><button id="37" onclick="startOnOff()">Start</button>
</div>
<script src="http://cdn.ably.io/lib/ably.min-1.js"></script>
<script>
var count = 0;
function startOnOff() {
var on = "37" + "on";
var off = "37" + "off";
if (counter % 2 == 0) {
toggleRelay(on);
count += 1;
} else if (count % 2 == 1) {
toggleRelay(off);
}
setInterval(startOnOff, 2000);
}
You have count in a few places and counter in one place where it should be count.
Assuming toggleRelay() is defined somewhere else in your code, try this:
var count = 0;
var on = "37" + "on";
var off = "37" + "off";
function startOnOff() {
if (count % 2 == 0) {
toggleRelay(on);
} else {
toggleRelay(off);
}
count += 1;
setTimeout(startOnOff, 2000);
}
count += 1; should be outside of the if conditional statement,
and use setTimeout() when calling startOnOff() recursively.
I've written a Javascript function that loads paginated content onto a page as you scroll to the bottom. The goal of this function is to increment the page number as you scroll and add that specific page number to the content already displayed, like Facebook does.
$(document).ready(function() {
$(window).scroll(function() {
var pagenumber = document.getElementById("pagenumber");
var results_box = document.getElementById("results_box");
var combo = pagenumber.innerHTML.split("|");
var pn = parseInt(combo[0]);
var last = parseInt(combo[1]);
results_box.innerHTML = "";
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
// ajax call get data from server and append to the div
results_box.innerHTML = "Loading...";
if (last != 1) {
if (pn < last) {
request_page(pn + 1);
} else if (pn == last) {
pagenumber.innerHTML = pn + 1 + "|" + last;
request_page(last);
} else {
results_box.innerHTML = "No More Content available";
}
}
}
});
});
the ajax "loading..." code not fire but when it randomly does it might load just two pages or duplicate some. My conjecture is that is has to do with the lack of a timestamp on each request for a new page.
The request_page function is fired once before the page is loaded, to display the first page of code, and the pagination "next" button when clicked accurately adds new content to the page,so my question is, how would i incorporate a timestamp into this function to effectively load data onto a page?
For clarity there is a div that displays the page number you're on out of total pages ex. 1 | 3 , the "last" variable is the last page ( 3 ) and the "pn" page number variable is the current page (1)
Basically I want to create next and previous buttons for a JQuery Image Gallery I'm working on. Each button has an id of "next" and "prev" respectively. What I'm trying to do is change a number that is in the source of the main image in the gallery (which has an id of mainImg). I have been able to target the number within the source of each image but I can't seem to increment it correctly and then replace the current image's source number with the new, incremented number. I tried using a while loop, for loop, and if statement but none of them worked correctly. To see the gallery that I have so far, I have it uploaded here: http://tiger.towson.edu/~abarso2/463/projecta/index.html If you go into my script.js file you'll see a block commented out at the bottom. That is the function I have so far that targets the number within the image's source and parses it to an integer. Thanks in advance for any help.
Here's what I have currently:
(function(){
var mainImg = $('#mainImg').attr('src');
var mainImgStr = mainImg.charAt(mainImg.length - 5);
var mainImgNum = parseInt(mainImgStr);
$('#next').click(function(){
});
}());
This should solve your problem
$(function(){
var mainImg = $('#mainImg');
var slidshow = $('#slideShow');
$('#next').click(function(){
var src = mainImg.attr('src').replace('thumb','shot');
var next = $('img[src="' + src +'"]', slidshow).next();
if(next.length){
mainImg.attr('src',next.attr('src').replace('thumb','shot'));
}
});
$('#prev').click(function(){
var src = mainImg.attr('src').replace('thumb','shot');
var prev = $('img[src="' + src +'"]', slidshow).prev();
if(prev.length){
mainImg.attr('src',prev.attr('src').replace('thumb','shot'));
}
});
});
Here is the revised code. The regexp will work better. The user can click the next button multiple times but no image will be skipped as the main image will only go to the next if and when the next image is loaded. So if you click next quickly 5 times only the next image will show (not skipping 4 images).
(function(){
// replace all non digit characters from src
// only the last set of numbers so www.123.com/image7.jpg
// will give us 7
function getNumber(src){
return parseInt(src.replace(/[\d]+(?=[\/])/g,"")
.replace(/[^\d]/g,""),10);
}
// replaces last number of a source with the number provided
// www.123.com/imgage7.jpg will be www.123.com/image8.jpg
// if number 8 is given
function setNumber(src,num){
return src.replace(/[\d]+(?![\d])/g,num);
}
var $mainImg = $('#mainImg');
$('#next').click(function(){
var src= $mainImg.attr('src'),
mainImgNum = getNumber(src);
var $img=$(document.createElement("img"));
$img.data("checkNext",false);
$img.on("load",function(){
// image exsist, load it as main image src
if($img.data("checkNext")===true){
$img.remove();
}else{
$mainImg.attr('src',$img.attr('src'));
$("#prev").show(1000);
$img.data("checkNext",true);
$img.attr('src',setNumber($img.attr('src'),
new String(mainImgNum+2));
});
$img.on("error",function(){
if($img.data("checkNext")===true){
$("#next").hide(1000);
}
// clean up
$img.remove();
});
$img.attr('src',setNumber(src,new String(mainImgNum+1)));
});
}());
Please can anyone see what is wrong in this code,
I have 2 class images with .man and .girl which contains 10 images in each.
next I have 2 div's #manCount and #girlCount which display total images number (10 in each)
when I move one image to #drop, It decrease 1 number from #manCount. So ther are total 10 images with class name .man, When the last image is moved to #drop I get a pop up that all images are processed.
now I also wants to process .girl class images but when i have both classess initialize it only work with .girl class.
function Dragger(c){
this.classname = c;
}
Dragger.prototype.Init = function(){
var classM = this.classname;
var manCount = parseInt($("#"+classM+"Count").text());
$("."+classM).draggable();
$("#drop").droppable({
drop: function() {
if(manCount <= 0){
alert("There are no more pictures left. " + classM );
return false;
}
manCount -= 1;
$("#"+classM+"Count").text(manCount);
}
});
};
var man = new Dragger("man");
man.Init();
above code runs just fine but when I initilize a new object
var man = new Dragger("man");
man.Init();
var girl = new Dragger("girl");
girl.Init();
It always pick girl object, any help where I am doing wrong?
It always return me female object on drag.
A screenshot of display: http://screensnapr.com/v/SrsyGz.png
Here is problem: http://screensnapr.com/v/hxrZYa.png
Thanks
Edit:
Ok i have fixed this issue by adding mouseover event, i am not sure how perfect it is thogh as i am pretty new to it but it works as expected
$(".man").mouseover(function(){
var man = new Dragger("man");
man.Init();
});
$(".girl").mouseover(function(){
var girl = new Dragger("girl");
girl.Init();
});
Maybe it’s because you are calling $('#drop').droppable() in the Init function, so it gets initiated more than once on the same element (#drop).