Change and cycle through images onclick in Javascript - javascript

I am just trying to cycle through all my images and then do nothing at the end via an onclick function. However I am having trouble. Any suggestions would be great.
<SCRIPT>
var quizImagesB = new Array();
quizImagesB[0]="images/dratiniB.png"
quizImagesB[1]="images/parasB.png"
quizImagesB[2]="images/mewB.png"
quizImagesB[3]="images/doduoB.png"
quizImagesB[4]="images/meowthB.png"
quizImagesB[5]="images/cloysterB.png"
quizImagesB[6]="images/ponytaB.png"
quizImagesB[7]="images/articunoB.png"
quizImagesB[8]="images/flareonB.png"
function updateImgB(){
for(var i=0; quizImagesB<.length; i++){
var url = 'url(' + quizImagesB[i] + ')'; //alters css
document.getElementById('pkmnImg').style.backgroundImage=url;
}
}
</SCRIPT>
<style type="text/css">
#pkmnImg
{
background-image: url(images/charmanderB.png);
background-repeat: no-repeat;
text-align: center;
width: 400px;
height: 450px;
margin-top: 10px;
margin-left: 15px;
}</style>
<FORM>
<INPUT TYPE="Button" VALUE="Change the image source" onClick="updateImgB();">
</FORM>
<div id ="pkmnImg"></div>

Ok this should work. Instead of looping through the array you want to increase the value of i by 1 on each click, allowing you to cycle through the array this way - see jsfiddle - https://jsfiddle.net/ffd7tmwy/1/
Javascript:
var quizImagesB = new Array();
quizImagesB[0]="images/dratiniB.png"
quizImagesB[1]="images/parasB.png"
quizImagesB[2]="images/mewB.png"
quizImagesB[3]="images/doduoB.png"
quizImagesB[4]="images/meowthB.png"
quizImagesB[5]="images/cloysterB.png"
quizImagesB[6]="images/ponytaB.png"
quizImagesB[7]="images/articunoB.png"
quizImagesB[8]="images/flareonB.png"
var i = 0
function updateImgB(){
var i = i + 1;
var url = 'url(' + quizImagesB[i] + ')';
document.getElementById('pkmnImg').style.backgroundImage=url;
}
HTML
<div id='pkmnImg'></div>
<form>
<input type="button" value="Change the image source" onClick="updateImgB()">
</form>

Related

How to pause and start gif using jQuery AJAX

I am a student and I am trying to start, pause and start a gif when a user clicks the gif, however I am stuck on how to add in this click function. I know that the the gif version of the object is .images.fixed_height.url and the still image is .images.fixed_height_still.url . If I try to append like below $(this) I get that images is undefined. How would I go by doing this? Currently 10 gifs show when you click the category. Thank you for any help in advance.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Giphy</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<style>
body {
background-image: url('http://www.efoza.com/postpic/2011/04/elegant-blue-wallpaper-designs_154158.jpg');
width: 100%;
}
button {
padding: 0 2%;
margin: 0 2%;
}
h4 {
font-size: 165%;
font-weight: bold;
color: white;
}
.container {
background-color: rgba(0, 0, 0, 0.2);
max-width: 1000px;
width: 100%;
}
.btn {
margin-top: 2%;
margin-bottom: 2%;
font-size: 125%;
font-weight: bold;
}
.guide {
padding: 3% 0 0 0;
}
.tag-row {
padding: 3% 0 0 0;
}
.category-row {
padding: 3% 0 ;
}
#photo {
padding-bottom: 3%;
}
</style>
</head>
<body>
<div class="container">
<div class="row text-center guide"><h4>Click a category and see the current top 10 most popular giphy's of that category!</h4></div>
<div class="row text-center tag-row" id="tags"></div>
<div class="row text-center category-row">
<input type="" name="" id="category"><button class="btn btn-secondary" id="addTag">Add Category</button>
</div>
</div>
<div class="container">
<div id="photo"></div>
</div>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
var tags = ["dog", "dolphin", "whale", "cat", "elephant", "otter"];
// Function for displaying movie data
function renderButtons() {
$("#tags").empty();
for (var i = 0; i < tags.length; i++) {
$("#tags").append('<button class="tag-buttons btn btn-primary">' + tags[i] + '</button>');
}
}
// Add tags function //
$(document).on('click', '#addTag', function(event) {
event.preventDefault();
var newTag = $("#category").val().trim();
tags.push(newTag);
$("#tags").append('<button class="tag-buttons btn btn-primary">' + newTag + '</button>');
});
// Tag button function //
$(document).on('click', '.tag-buttons', function(event) {
// Keeps page from reloading //
event.preventDefault();
var type = this.innerText;
console.log(this.innerText);
var queryURL = "http://api.giphy.com/v1/gifs/search?q=" + window.encodeURI(type) + "&limit=10&api_key=dc6zaTOxFJmzC";
$.ajax({
url: queryURL,
method: "GET"
}).done(function(response) {
for (var i = 0; i < response.data.length; i++) {
$("#photo").append('<img src="' + response.data[i].images.fixed_height_still.url + '" class="animate">');
$('.animate').on('click', function() {
$(this).remove().append('<img src="' + response.data[i].images.fixed_height.url + '" class="animate">');
console.log($(this));
});
}
});
$("#photo").empty();
});
renderButtons();
</script>
</body>
</html>
The difference between fixed_height and fixed_height_still will solve the problem. if you look closely the urls differ only by name_s.gif and name.gif.
So you can simply swap the two images to create a player. This will act like a play and stop. Not play and pause. But in a small gif I don't think pause really matter, stop and pause will look similar.
adding class name to the #photo
$("#photo").append('<img class="gif" src="' + response.data[i].images.fixed_height_still.url + '">');
event handler which will control play and stop
$('body').on('click', '.gif', function() {
var src = $(this).attr("src");
if($(this).hasClass('playing')){
//stop
$(this).attr('src', src.replace(/\.gif/i, "_s.gif"))
$(this).removeClass('playing');
} else {
//play
$(this).addClass('playing');
$(this).attr('src', src.replace(/\_s.gif/i, ".gif"))
}
});
jsfiddle demo
https://jsfiddle.net/karthick6891/L9t0t1r2/
you can use this jquery plugin http://rubentd.com/gifplayer/
<img class="gifplayer" src="media/banana.png" />
<script>
$('.gifplayer').gifplayer();
</script>
you can control like this
Use these methods to play and stop the player programatically
$('#banana').gifplayer('play');
$('#banana').gifplayer('stop');
youll find more details here https://github.com/rubentd/gifplayer

how do I make margins work on divs created dynamically in my JS?

HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"/>
<link rel="stylesheet" type="text/css" media="all" href="css/animate.min.css"/>
<link href="http://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"/>
<link rel="stylesheet" href="css/thisProject.css"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<h1 class="text-primary">Wiki Article Search</h1>
<div>
<input type="text" id="input"/>
<button id="search">Search</button>
<a id="random" class="btn btn-primary" target="_blank" href="http://en.wikipedia.org/wiki/Special:Random">Press For Random</a>
</div>
</br>
<div id="bodyDiv">
</div>
<script src="wikiViewer.js"></script>
</body>
</html>
JavaScript:
(function(){
var searchBtn = document.getElementById('search');
//var body = document.getElementsByTagName('body')[0];
var input = document.getElementById("input");
var bodyDiv = document.getElementById('bodyDiv')
$(document).ready(function(){
searchBtn.addEventListener('click', searchWiki);
function searchWiki(){
bodyDiv.innerHTML = "";
var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch='
if (input.value === ""){
return;
}
var searchTerm = input.value.replace(/\s/g, '%20');
url = url + searchTerm + '&callback=?';
$.getJSON(url, domMod); //change fileName to be whatever we wish to search
function domMod(json){ //what to do with dom based on json file NOTE WE NEED TO FIRST CHECK ANDREMOVE PREVIOUS SEARCH CONTENT
var entry;
if (!json.hasOwnProperty('query')){
return;
}
if (!json.query.hasOwnProperty('pages')){
return;
}
json = json.query.pages;
var keys = Object.keys(json);
var keysLength = keys.length;
for (var i = 0; i < keysLength; i++){
entry = json[keys[i]];
var outterDiv = document.createElement('div');
outterDiv.className = "entry";
var imageDiv = document.createElement('div');
imageDiv.className = "entryImg";
var entryDiv = document.createElement('div');
entryDiv.className = "entryTxt";
outterDiv.appendChild(imageDiv);
outterDiv.appendChild(entryDiv);
entryDiv.innerHTML = '<h2>' + entry.title + '</h2>' + '<p>' + entry.extract + '</p>'
if (entry.hasOwnProperty('thumbnail')){ //add image to our imageDiv child of entryDiv
imageDiv.style.backgroundImage = "url('" + entry.thumbnail.source + "')"
}
var br = document.createElement('br');
bodyDiv.appendChild(outterDiv); //appendChild to the Body
bodyDiv.appendChild(br);
}
}
}
});
}())
CSS:
input{
width:180px;
}
.entry{
width:90%;
margin-left:auto;
margin-right:auto;
height: 140px;
}
.entryTxt{
margin-left: 5px;
}
.entryImg{
width:125px;
height:125px;
margin-right: 5px;
background-repeat: no-repeat;
background-size: contain;
background-position: center;
float:left;
}
#bodyDiv{
width: 100%;
height: 1600px;
}
The javascript code runs through each return object that a wikipedia API returns based on a user's search term. It then puts the image in a div with class "entryImg" and the entry text in a div called "entryTxt". It then puts each of these in a div labeled outterDiv which is appended to the div already in my HTML with id "bodyDiv." My question is, in each outterDiv why are the picture and the text divs so close to each other regardless of how much I change the margins. I put 5px on the texts left margin and 5 px on the picture divs right margin as can be seen and the change isn't appearing in the browser. Why is this and how can I fix it?
based on your javascript code the generated html would be
<div id="bodyDiv">
<div class="entry">
<div class="entryImg"></div>
<div class="entryTxt">
<h2>lorem ipsum</h2>
<p>lorem ipsum</p>
</div>
</div>
</div>
and, with your css, you ca increase the space between image and text by
increasing margin-right on .entryImg
.entryImg {
margin-right: 10px;
}
or, by increasing margin-left on .entryTxt after adding overflow: hidden; on it.
.entryTxt {
margin-left: 10px;
overflow: hidden;
}
check this fiddle

element height() not adding + 200?

I would like to scroll to the end of the container. The element is having new items added via ajax on click, so I am recalculating its height each time I click to load more. The page scrolls fine but I would like to also add the navigation height in order to have the exact pixels. It looks like it is not adding + 224 tho
Html
lorem
New items are added via a click and ajax.
Css
nav {
height: 90px;
}
#container {
margin-top: 104px;
margin-bottom: 120px;
}
Jquery
var page = $("html, body");
var pos = $("#container").height() + 224;
page.animate({scrollTop: pos}, 1000);
I think you want something like this no ?
var page = $("html, body");
console.log($("#t").height());
var pos = $("#t").height() - 500;
console.log(pos);
page.animate({scrollTop: pos}, 1000);
div{
height: 1000px;
width: 50px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="t"></div>
you can use scrollIntoView for last added item
var j=0;
function Add(){
var item=null;
for(var i=0;i<20;i++){
j++
item= $('<div class="item">'+j+'</div>').appendTo("#container")
}
item[0].scrollIntoView()
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" onclick="Add()" Value="Add" />
<div id="container"></div>

jQuery an element with for a url

I have 3 divs with data-image="1" data-image="2" data-image="3".
And I have variable $img_nubmer.
I need to take the div's background-image url from element with data-image = $img_nubmer.
Something like $url = $("'.img[data-image="+$img_number+"']").css("background-image")
How could I do that please?
I would try
$img_number = 5; // just an example
$url = $("img[data-image='"+$img_number+"']").css("background-image"); // grab the background property
So for a full example:
window.getURL = function() {
$img_number = $('[type="number"]').val();
$url = $("[data-image='" + $img_number + "']").css("background-image");
$url = $url.replace('url(', '').replace(')', ''); // lose the extra details
alert($url);
}
div.image {
background-image: url('http://graph.facebook.com/205500370/picture?type=large');
height: 150px;
width: 150px;
}
div {
display: inline-block;
vertical-align: middle;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image" data-image="5"></div>
<div>
<input type="number" value="5" />
<br>
<button onclick="getURL()">Get Image URL</button>
</div>
You can add the variable into your selector as such:
var img_number = 1;
$('img[data-image="'+img_number+'"]');
View Codepen example

Apps Script Template HTML Breaks on Success Handler

Searched, but wasn't able to find any similar problems or solutions.
I have some templated HTML which builds a form based on data from a spreadsheet, as I have a variable number of dropdowns and options in those dropdowns.
On click of submit I want to display a spinning gif to the user, so they know it is processing.
If the backend code in code.gs passes the input through all the tests I want to update a div with a success message, if any of the checks fail with an error message.
I've got this to work, before with the create .createHtmlOutputFromFile method, but now with .createTemplateFromFile it just wipes the whole page.
HTML template
<style type="text/css">
#import url(http://fonts.googleapis.com/css?family=Open+Sans:400,600,300);
#container{
padding-left:10px;
font-family: 'Open Sans', Arial, sans-serif;
}
#header{
width: 75%;
margin: 0 auto;
text-align: center;
margin-bottom:10px;
}
form{
text-align: center;
margin-top:10px;
}
#nameField{
width:400px;
margin-bottom:10px;
}
#reqIndic{
color:#FF0000;
}
select{
margin-top: 5px;
width:150px;
}
#submit{
margin-top:20px;
width:125px;
height:40px;
}
#confirmation{
width: 30%;
margin: 0 auto;
min-height:60px;
border-radius: 5px;
}
#padding{
width: 30%;
margin: 0 auto;
min-height:60px;
border-radius: 5px;
}
</style>
<div id="container">
<div id="header">
<h2>Cheltenham Classic</h2>
</div>
<br>
<form name="projectsForm">
<span id="reqIndic">*</span>
<span> Name</span>
<input id="nameField" type="text" name="name" required>
<br>
<? for (var race in races) { ?>
<span><?= race ?></span>
<select>
<? for (var i = 0; i < races[race].length; i++) { ?>
<option value="<?= races[race][i] ?>"><?= races[race][i] ?></option>
<? } ?>
</select>
<br>
<? } ?>
<br>
<input id="submit" type="submit" value="Submit Form" onclick="google.script.run
.withSuccessHandler(updateDiv)
.onEvent(this.parentNode);spinner()">
</form>
</div>
<div id="confirmation" style ="text-align:center"></div>
<div id="padding" style ="text-align:center"></div>
<script type="text/javascript">
function updateDiv(returnValue){
alert('debug');
var div = document.getElementById('confirmation');
if(returnValue == false){
var errStr = '<p>ERROR: Please check your rankings for blank fields or multiple entries of the same project and re-submit your rankings</p>';
div.innerHTML = errStr;
}
else{
div.innerHTML = '<p>Success! Your results were submitted successfully</p>';
}
}
function spinner(){
var div = document.getElementById('confirmation');
div.innerHTML = '<img src="http://loadinggif.com/images/image-selection/32.gif">'
}
</script>
Back end code
I've cut the onEvent function right down to just returning an object with a key value pair without making any checks.
The updateDiv function runs and the alert shows then the entire page is wiped.
function doGet(){
var raceForm = HtmlService.createTemplateFromFile('RaceForm');
raceForm.races = getRaces();
return raceForm.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function onEvent(e){
return {'valid': true};
}
function getRaces(){
var url = //spreadsheet url
var wb = SpreadsheetApp.openByUrl(url);
var ws = wb.getSheetByName('Races Log');
var racesObj = {};
var wsValues = ws.getDataRange().getValues();
for(var i = 0; i <wsValues.length;i++){
var race = wsValues[i][0];
racesObj[race] = [];
racesObj[race].push('0');
for(var j = 1; j<wsValues[i].length;j++){
racesObj[race].push(wsValues[i][j]);
}
}
return racesObj;
}
Any help much appreciated.
If I hard code the racesObj object:
var racesObj = {one:["one","two"], two:["one", "two"], "races":["belmont", "kentucky"]};
The page looks like this: (Using the template)
If I click the submit button, I get this:

Categories