How to not insert duplicate images? - javascript

So what I have done is that, I have created a function that retrives data(images) from the database using XMLHttpRequest and appends it to td every 5000 milliseconds. Now as they are appended every 5000 milliseconds, if the data retrieved is not changed then it keeps appending the same data again and again. To stop it I attached custom attributes to the images with their IDs but I am not sure how would I stop it from appending duplicated items. This is my JS:
function getAlbumImages() {
var xhr2 = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr2.open('GET', 'admin/images_data.php');
xhr2.onreadystatechange = function(e) {
if(xhr2.readyState == 4 && xhr2.status == 200) {
var album_photos = JSON.parse(xhr2.responseText);
for(var i = 0; i < album_photos.length; i++) {
var td = document.createElement('td');
var imagewrap = document.createElement('div');
imagewrap.className = "image-wrap";
var imagemenu = document.createElement('div');
imagemenu.className = "image-menu";
var imagemenuimg1 = document.createElement('img');
imagemenuimg1.src = "img/edit_img.png";
var imagemenuimg2 = document.createElement('img');
imagemenuimg2.src = "img/close.png";
var imagewrapimg = document.createElement('img');
imagewrapimg.className = "thumbnail";
imagewrapimg.src = "admin/album_photos/" + album_photos[i].Image_Path;
imagewrapimg.setAttribute("data-image-id", album_photos[i].Image_ID);
document.getElementById("tiare").appendChild(td);
td.appendChild(imagewrap);
imagewrap.appendChild(imagemenu);
imagemenu.appendChild(imagemenuimg1);
imagemenu.appendChild(imagemenuimg2);
imagewrap.appendChild(imagewrapimg);
}
}
}
xhr2.send(null);
}
setInterval(function(){
getAlbumImages();
}, 5000);
And the markup:
<html>
<head>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<!-- <div class="big_image" id="drop_zone">
<img src="" id="big_img" />
</div -->
<div class="images_holder">
<div class="header">
Album Name - Photo Album
<span class="close"><img src="img/close.png" /></span>
</div>
<div class="body">
<table width="80%">
<tr id="tiare">
</tr>
</table>
</div>
</div>
<div id="drop_zone">
Drag/Drop images to upload.
</div>
<div style="height: 30px; width: 80%; color: white; text-align: center; margin: 0 auto;">
<p id="progress_bar" style="width: 0%; background-color: red;"></p>
</div>
<script src="js/script.js"></script>
</body>
</html>
This is what happens the first time:
And this is what happens afterwards:
See the duplicated images
How can I stop it from appending the duplicated? Thanks in advance. :)
P.S: NO JQUERY ALLOWED. :)

Just check if instance with same ID or URL is at page before insert
if(document.querySector('div.thumbnail[data-image-id="' + album_photos[i].Image_ID + '"]')){
continue;
}
Or save list of all inserted id's in memory ( as array or object { id: url } ) and check if this item already loaded

Related

Need help fixing a bug in a browser game

This is a very simple browser memory game which you need to to flip all the matched cards in order to win.
The bug :
In the game if you click fast enough you can flip more than 2 cards.
I've tried a lot to fix it but couldn't figure it out by myself. I would appreciate any help in solving this issue as I am new to JavaScript and it's still hard for me fix those basic bugs.
Game files:
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My App</title>
<link rel="stylesheet" href="css/game.css" />
</head>
<body>
<button class="Change User" onclick="change(this)">Change User</button>
<div class="header">
<img src="img/layout/logo.png">
<h1>Memory Monsters</h1>
<p id="Play Again"></p>
</div>
<div class="card" data-card="1" onclick="cardClicked(this)">
<img src="img/cards/1.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="7" onclick="cardClicked(this)">
<img src="img/cards/7.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="1" onclick="cardClicked(this)">
<img src="img/cards/1.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="7" onclick="cardClicked(this)">
<img src="img/cards/7.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="5" onclick="cardClicked(this)">
<img src="img/cards/5.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="5" onclick="cardClicked(this)">
<img src="img/cards/5.png">
<img class="back" src="img/cards/back.png">
</div>
<script src="js/game.js"></script>
</body>
</html>
javascript:
var getElementsByClassName = prompt ('What is your name?');
window.localStorage.setItem ('name', 'dan');
function change(username) {
prompt('What is your name?');
}
// Those are global variables, they stay alive and reflect the state of the game
var elPreviousCard = null;
var flippedCouplesCount = 0;
// This is a constant that we dont change during the game (we mark those with CAPITAL letters)
var TOTAL_COUPLES_COUNT = 3;
// Load an audio file
var audioWin = new Audio('sound/win.mp3');
// This function is called whenever the user click a card
function cardClicked(elCard) {
// If the user clicked an already flipped card - do nothing and return from the function
if (elCard.classList.contains('flipped')) {
return;
}
// Flip it
elCard.classList.add('flipped');
// This is a first card, only keep it in the global variable
if (elPreviousCard === null) {
elPreviousCard = elCard;
} else {
// get the data-card attribute's value from both cards
var card1 = elPreviousCard.getAttribute('data-card');
var card2 = elCard.getAttribute('data-card');
// No match, schedule to flip them back in 1 second
if (card1 !== card2){
setTimeout(function () {
elCard.classList.remove('flipped');
elPreviousCard.classList.remove('flipped');
elPreviousCard = null;
}, 1000)
} else {
// Yes! a match!
flippedCouplesCount++;
elPreviousCard = null;
// All cards flipped!
if (TOTAL_COUPLES_COUNT === flippedCouplesCount) {
audioWin.play();
// and finally add a button to call resetCard()
document.getElementById("Play Again").innerHTML =
'<button onclick="resetCard();">Play Again</button>';
}
}
}
}
function resetCard() {// to erase the flipped classes
var cardclass = document.getElementsByClassName("card");
for (i = 0; i < cardclass.length; i++) {
cardclass[i].classList.remove("flipped");
document.getElementById("Play Again").innerHTML = "";
}
}
CSS:
.header {
background-color: lightblue;
padding: 20px;
border-bottom: 10px solid darkcyan;
color:darkcyan;
font-size: 1.5em;
text-align: center;
}
.header img {
float:right;
}
.card {
background-color: pink;
height: 165px;
width: 165px;
float: left;
margin: 5px;
}
.card img {
position: absolute;
}
.flipped .back {
display: none;
}
i made a game like this. you need to create a variable that starts on 0
let tries = 0;
then add one to it each time a card is selected. make sure to not allow it to count if a card that is already flipped is clicked again. here is some of the code from the function that is run on my onclick. I am using a React framework, but if you write this logic in your JS function, it is what you will need to make it work
selected = (event) => {
if (canClick === true) {
let id = event.currentTarget.id; //card0
let idString = id.toString(); //"card0"
//ONLY ALLOW A CARD TO BE CLICKED IF ITS FACE DOWN
if (this.state[idString] === cardBack) {
idString = idString.replace(/card/g, ''); //"0"
this.setState({[id] : arrayRandom[idString]});
//FIRST PICK
if (counter % 2 == 1) {
curCard1 = arrayRandom[idString].toString();
id1 = id;
counter++;
//SECOND PICK
} else {
//MAKE SURE A CARD DOESN'T GET SELECTED TWICE IN A ROW AND STAY FACE UP
if (id === id1) {
console.log("Select a different card for your second pick");
} else {
counter++;
tries++;
canClick = false; //STOP USER FROM SELECTING ANOTHER CARD
curCard2 = arrayRandom[idString].toString();
id2 = id;
setTimeout(() => {canClick = true}, 1000); //USER CAN PICK AGAIN IN 1 SEONCD
//IF THERE'S A MATCH - CARDS STAY FLIPPED, SCORE INCREASES BY 1
if (curCard1 == curCard2) {
score = score + 1;
//IF THERE'S NO MATCH - CARDS FLIP FACE DOWN AFTER A SECOND
} else {
setTimeout(() => {
this.setState({[id1]: cardBack});
this.setState({[id2]: cardBack});
}, 1000);
}
}
}
} else {
console.log("This card has already been flipped, select another one");
}
}
}
here is my game
https://reactcardmatch.netlify.com/

How can I update attributes with jQuery?

$(document).ready(function() {
var hero_image = new Array();
hero_image[0] = new Image();
hero_image[0].src = 'assets/images/link.png';
hero_image[0].id = 'image';
hero_image[1] = new Image();
hero_image[1].src = 'assets/images/bongo.png';
hero_image[1].id = 'image';
hero_image[2] = new Image();
hero_image[2].src = 'assets/images/gandondorf.jpg';
hero_image[2].id = 'image';
hero_image[3] = new Image();
hero_image[3].src = 'assets/images/queen.png';
hero_image[3].id = 'image';
var young_hero = ["Link", "Bongo Bongo", "Gandondorf", "Queen Gohma"];
var health = [100, 70, 120, 50];
var attack_power = [];
var counter_power = [];
console.log(hero_image[0]);
function it_is_over_9000(){
for (var i = 0; i < young_hero.length; i++) {
var x = Math.floor(Math.random(attack_power)*20) + 3;
var y = Math.floor(Math.random(attack_power)*10) + 3;
attack_power.push(x);
counter_power.push(y);
}
}
function ready_board(){
it_is_over_9000();
for (var i = 0; i < young_hero.length; i++) {
var hero_btns = $("<button>");
hero_btns.addClass("hero hero_button");
hero_btns.attr({
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
hero_btns.text(young_hero[i]);
hero_btns.append(hero_image[i]);
hero_btns.append(health[i]);
$("#buttons").append(hero_btns);
}
}
function char(){
$(".hero_button").on("click", function() {
var hero = $(this);
var hero_select = hero.data('index');
for (var i = 0; i < young_hero.length; i++) {
//var attack = ;
if (i != hero_select){
var enemies = $("<button>");
enemies.addClass("hero enemy");
enemies.attr({
"data-power" : it_is_over_9000(),
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
enemies.text(young_hero[i]);
enemies.append(hero_image[i]);
enemies.append(health[i]);
$("#battle").append(enemies);
}
}
$("#buttons").html($(this).data('name','health','image'));
defender();
});
}
function defender(){
$(".enemy").on("click", function() {
var enemy = $(this);
var enemy_select = enemy.data("index");
console.log(enemy_select);
for (var i = 0; i < young_hero.length; i++) {
if (i == enemy_select) {
var defender = $("<button>");
defender.addClass("hero defender");
defender.attr({
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
defender.text(young_hero[i]);
defender.append(hero_image[i]);
defender.append(health[i]);
$("#defend").append(defender);
$(this).remove();
}
}
});
}
$(".defend_button").on("click" , function(){
if($(".defender").data("health") == 0){
$(".defender").remove();
}
$(".defender").attr({
"data-health": $(".defender").data("health") - $(".hero_button").data("attack")
});
});
ready_board();
char();
});
I am trying to make a RPG game and I have the characters being generated the way I want them too but on the $(".defend_button").on("click" , function() at the end it doesn't update the data-health as it should. It only updates once but upon many clicks on the defend-button it doesn't update past the first time.
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Zelda</title>
<script type='text/javascript' src='https://code.jquery.com/jquery-2.2.0.min.js'></script>
<script type = "text/javascript" src = "assets/javascript/game.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>
<style type="text/css">
.hero { width: 125px; height:150px; border-style: solid; padding: 2px; float: left; margin: 2px; float: left; }
.letter-button-color { color: darkcyan; }
.fridge-color { color: orange; }
#display { margin-top:78px; height:500px; width:220px; margin-left:60px; }
#buttons { padding-top:60px; }
#clear { margin-left: 20px; font-size: 25px; color: black; border-style: solid; width: 100px; }
#image{width: 100px; height: 100px; margin-left: 10px; }
</style>
<body>
<div class="row">
<div class="col-md-8">Select Your Character</div>
</div>
<div class="row">
<div id="buttons" class="col-md-8"></div>
</div>
<div class="row">
<div id="battle" class="col-md-8">
</div>
</div>
<div class="row">
<div class="col-md-8">
<button class="btn btn-primary defend_button">Defend</button>
</div>
</div>
<div class="row">
<div id="defend">
</div>
</div>
</body>
</html>
You have to use .data() to update the health value.
var battleResult = $(".defender").data("health") - $(".hero_button").data("attack");
console.log("battleResult should be: "+battleResult );
$(".defender").data({
"health": battleResult
});
I played a little with your game.
I found how to update the health display below the image too...
Since only updating the data wasn't changing anything on the screen.
So, I left the above code there, for you to see it is effectively working.
But since you have to re-create the button to update health on scrreen... It is kind of useless.
I also fixed the death condition
from if($(".defender").data("health") == 0){
to if($(".defender").data("health") <= 0){
I have to stop here before changing to much things.
See it in CodePen
Check your loop in it_is_over_9000(), because I think it is running uselessly too often.
And a dead defender has to be "buried" (lol).
Because when it is killed, a click on the defend button is kind of ressurrecting it.
;)
Try setting the attribute like this. Also, I recommend putting $(".defender") in a variable so you aren't requerying it each time.
var defender = $(".defender");
var loweredHealth = defender.data("health") - $(".hero_button").data("attack");
defender.attr('data-health`, loweredHealth);
Update:
It looks like the $('.defender') call will return multiple items. You either need to select a specific defender or iterate through them individually like so:
$('.defender').each(function(i, nextDefender) {
var loweredHealth = nextDefender.data("health") - $(".hero_button").data("attack");
nextDefender.attr('data-health`, loweredHealth);
});`

JQuery Remove not removing specified div

I have a small page on which you can add squares of different colors to a div with a button. After adding them, you can remove them by double clicking any of the squares created.
My code works well, when adding elements. However when I want to remove a square, I just get to remove one and after that I can´t make the element disappear on HTML even though the counter does decrease. I´m a doing something wrong with the remove() function? Right now I´m just focusing on the blue (Azul) color.
Here´s my code
https://jsfiddle.net/kdwyw0mc/
var azules = 0;
var rojos = 0;
var amarillos = 0;
var verdes = 0;
function eliminar(cuadro){
azules = parseInt(jQuery('#num-azules').text());
verdes = parseInt(jQuery('#num-verdes').text());
rojos = parseInt(jQuery('#num-rojos').text());
amarillos = parseInt(jQuery('#num-amarillos').text());
if(cuadro[0].classList[1]=='blue'){
azules = azules -1;
}
else if(cuadro[0].classList[1]=='red'){
rojos--;
}
else if(cuadro[0].classList[1]=='yellos'){
amarillos--;
}
else if(cuadro[0].classList[1]=='green'){
verdes--;
}
cuadro.remove();
jQuery('#num-azules').text(azules);
jQuery('#num-verdes').text(verdes);
jQuery('#num-rojos').text(rojos);
jQuery('#num-amarillos').text(amarillos);
}
function agregar(){
jQuery('span#num-azules').val(azules);
var numCuadros = jQuery("#numero").val();
var color = $('#color option:selected').text();
for( i = 0; i< numCuadros; i++){
if(color=='Azul'){
/*jQuery(".square").append(function(){
return jQuery('<div class="square blue"> </div>').ondblclick(eliminar);
})*/
var newSquare = jQuery('<div class="square blue"> </div>')
var a = jQuery(".squares").append(newSquare);
newSquare.dblclick(function(){eliminar(newSquare);})
azules += 1;
}
else if(color=='Rojo'){
jQuery(".squares").append('<div class="square red"> </div>')
rojos+= 1;
}
else if(color=='Amarillo'){
jQuery(".squares").append('<div class="square yellow"> </div>')
amarillos+= 1;
}
else if(color=='Verde'){
jQuery(".squares").append('<div class="square green"> </div>')
verdes+= 1;
}
}
jQuery('#num-azules').text(azules);
jQuery('#num-verdes').text(verdes);
jQuery('#num-rojos').text(rojos);
jQuery('#num-amarillos').text(amarillos);
}
/*
* jQuery("#agregar").click(function(){
agregar();
});
VS
jQuery("#agregar").click(agregar());
* */
jQuery('#num-azules').text(azules);
jQuery('#num-verdes').text(verdes);
jQuery('#num-rojos').text(rojos);
jQuery('#num-amarillos').text(amarillos);
jQuery("#agregar").click(function(){
agregar();
});
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="styles/reset.css"/>
<link rel="stylesheet" href="styles/main.css"/>
</head>
<body>
<div class="main-content">
<div class="toolbar">
Numero Cuadrados: <input id="numero"type="text"/>
<select id="color" name="color">
<option value="azul">Azul</option>
<option value="rojo">Rojo</option>
<option value="amarillo">Amarillo</option>
<option value="verde">Verde</option>
</select>
<button id="agregar">Agregar</button>
</div>
<div class="squares">
</div>
<div class="numeros">
<p>Azules: <span id="num-azules">0</span> </p>
<p>Rojos: <span id="num-rojos">0</span></p>
<p>Verde: <span id="num-verdes">0</span></p>
<p>Amarillo: <span id="num-amarillos">0</span></p>
</div>
</div>
<script src="scripts/jquery-1.11.3.min.js"></script>
<script src="scripts/main.js"></script>
</body>
</html>
This is an inefficient way of registering / listening to events, it is better to delegate the event handling to a wrapper (parent) container:
$("#container").on("dblclick", ".square", function(){
$(this).remove();
)};
on works for dynamically created elements; since the container was already in the DOM, it can continue listening to events coming from any other, newly created child element that has class .square.
http://api.jquery.com/on/
Edit:
One way of solving the counter problem would be to do something like this:
var StateObj = function(){
this.counter = 0;
this.arrSquares = [];
this.increaseCounter = function(){
this.counter += 1;
},
this.decreaseCounter = function(){
this.counter -= 1;
},
this.addSquare = function(id, color){
this.arrSquares.push({id: id, color: color});
},
this.getSquareById = function(id){
return square = $.grep(this.arrSquares, function(){ return id == id; });
}
}
var stateObj = newStateObj();
$("#container").on("dblclick", ".square", function(e){
$(this).remove();
var id = $(e.currentTarget).attr("id");
stateObj.increaseCounter();
console.log(stateObj.counter);
)};

JavaScript file not working in browser, however it does work in codepen

I am building a webpage that uses a JavaScript application called photo swipe (http://photoswipe.com/).
I cannot get the JavaScript to run in my browser locally.
I have tested this in several different browsers. I have double checked all file names (including capitalization) and locations as referenced in the code. All the files are stored on my computer in the same folder, in the correct format. I have tried clearing the cache. The external libraries required to run the JavaScript are referenced in the files as they are in Code Pen.
It works in Code Pen just fine like so:
http://codepen.io/anon/pen/XJEWEN
Here are the files I am trying to run on the browser locally:
HTML
<!DOCTYPE html>
<html>
<head>
<!-- Core JS file -->
<script src="http://photoswipe.s3-eu-west-1.amazonaws.com/pswp/dist/photoswipe.min.js"></script>
<!-- UI JS file -->
<script src="http://photoswipe.s3-eu-west-1.amazonaws.com/pswp/dist/photoswipe-ui-default.min.js"></script>
<!-- Link to JS document as it is in code-pen, on computer stored in same folder as HTML document-->
<script type="text/javascript" src="document.js"></script>
<!-- Link to main css document as it is in code-pen, on computer stored in same folder as HTML document-->
<link type="text/css" rel="stylesheet" href="main.css"/>
<!-- Core CSS file -->
<link rel="stylesheet" href="http://photoswipe.s3.amazonaws.com/pswp/dist/photoswipe.css"/>
<!-- Skin CSS file (styling of UI - buttons, caption, etc.)
In the folder of skin CSS file there are also:
- .png and .svg icons sprite,
- preloader.gif (for browsers that do not support CSS animations) -->
<link rel="stylesheet" href="http://photoswipe.s3.amazonaws.com/pswp/dist/default-skin/default-skin.css"/>
<meta charset="UTF-8">
<meta name="keywords" content="Photo, Web Design">
<meta name="description" content="Examples of ways that photos can be presented online">
<html lang="en-US">
</head>
<body>
<h2>Gallery 1</h2>
<div class="my-simple-gallery" itemscope itemtype="http://schema.org/ImageGallery">
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_b.jpg" itemprop="contentUrl" data-size="964x1024">
<img src="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_m.jpg" itemprop="thumbnail" alt="Image description" />
</a>
<figcaption itemprop="caption description">Image caption 2.1</figcaption>
</figure>
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="https://farm7.staticflickr.com/6175/6176698785_7dee72237e_b.jpg" itemprop="contentUrl" data-size="1024x683">
<img src="https://farm7.staticflickr.com/6175/6176698785_7dee72237e_m.jpg" itemprop="thumbnail" alt="Image description" />
</a>
<figcaption itemprop="caption description">Image caption 2.2</figcaption>
</figure>
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="https://farm6.staticflickr.com/5023/5578283926_822e5e5791_b.jpg" itemprop="contentUrl" data-size="1024x768">
<img src="https://farm6.staticflickr.com/5023/5578283926_822e5e5791_m.jpg" itemprop="thumbnail" alt="Image description" />
</a>
<figcaption itemprop="caption description">Image caption 2.3</figcaption>
</figure>
</div>
<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
<!-- Background of PhotoSwipe.
It's a separate element, as animating opacity is faster than rgba(). -->
<div class="pswp__bg"></div>
<!-- Slides wrapper with overflow:hidden. -->
<div class="pswp__scroll-wrap">
<!-- Container that holds slides. PhotoSwipe keeps only 3 slides in DOM to save memory. -->
<!-- don't modify these 3 pswp__item elements, data is added later on. -->
<div class="pswp__container">
<div class="pswp__item"></div>
<div class="pswp__item"></div>
<div class="pswp__item"></div>
</div>
<!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
<div class="pswp__ui pswp__ui--hidden">
<div class="pswp__top-bar">
<!-- Controls are self-explanatory. Order can be changed. -->
<div class="pswp__counter"></div>
<button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
<button class="pswp__button pswp__button--share" title="Share"> </button>
<button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
<button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
<!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
<!-- element will get class pswp__preloader--active when preloader is running -->
<div class="pswp__preloader">
<div class="pswp__preloader__icn">
<div class="pswp__preloader__cut">
<div class="pswp__preloader__donut"></div>
</div>
</div>
</div>
</div>
<div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
<div class="pswp__share-tooltip"></div>
</div>
<button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
</button>
<button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
</button>
<div class="pswp__caption">
<div class="pswp__caption__center"></div>
</div>
</div>
</div>
</section>
</div>
</div>
</body>
</html>
CSS
.my-simple-gallery {
width: 100%;
float: left;
}
.my-simple-gallery img {
width: 100%;
height: auto;
}
.my-simple-gallery figure {
display: block;
float: left;
margin: 0 5px 5px 0;
width: 150px;
}
.my-simple-gallery figcaption {
display: none;
}
*{margin:0;}
.my-simple-gallery {
width: 100%;
float: left;
}
.my-simple-gallery img {
width: 100%;
height: auto;
}
.my-simple-gallery figure {
display: block;
float: left;
margin: 0 5px 5px 0;
width: 150px;
}
.my-simple-gallery figcaption {
display: none;
}
JavaScript
var initPhotoSwipeFromDOM = function(gallerySelector) {
// parse slide data (url, title, size ...) from DOM elements
// (children of gallerySelector)
var parseThumbnailElements = function(el) {
var thumbElements = el.childNodes,
numNodes = thumbElements.length,
items = [],
figureEl,
childElements,
linkEl,
size,
item;
for(var i = 0; i < numNodes; i++) {
figureEl = thumbElements[i]; // <figure> element
// include only element nodes
if(figureEl.nodeType !== 1) {
continue;
}
linkEl = figureEl.children[0]; // <a> element
size = linkEl.getAttribute('data-size').split('x');
// create slide object
item = {
src: linkEl.getAttribute('href'),
w: parseInt(size[0], 10),
h: parseInt(size[1], 10)
};
if(figureEl.children.length > 1) {
// <figcaption> content
item.title = figureEl.children[1].innerHTML;
}
if(linkEl.children.length > 0) {
// <img> thumbnail element, retrieving thumbnail url
item.msrc = linkEl.children[0].getAttribute('src');
}
item.el = figureEl; // save link to element for getThumbBoundsFn
items.push(item);
}
return items;
};
// find nearest parent element
var closest = function closest(el, fn) {
return el && ( fn(el) ? el : closest(el.parentNode, fn) );
};
// triggers when user clicks on thumbnail
var onThumbnailsClick = function(e) {
e = e || window.event;
e.preventDefault ? e.preventDefault() : e.returnValue = false;
var eTarget = e.target || e.srcElement;
var clickedListItem = closest(eTarget, function(el) {
return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
});
if(!clickedListItem) {
return;
}
// find index of clicked item
var clickedGallery = clickedListItem.parentNode,
childNodes = clickedListItem.parentNode.childNodes,
numChildNodes = childNodes.length,
nodeIndex = 0,
index;
for (var i = 0; i < numChildNodes; i++) {
if(childNodes[i].nodeType !== 1) {
continue;
}
if(childNodes[i] === clickedListItem) {
index = nodeIndex;
break;
}
nodeIndex++;
}
if(index >= 0) {
openPhotoSwipe( index, clickedGallery );
}
return false;
};
// parse picture index and gallery index from URL (#&pid=1&gid=2)
var photoswipeParseHash = function() {
var hash = window.location.hash.substring(1),
params = {};
if(hash.length < 5) {
return params;
}
var vars = hash.split('&');
for (var i = 0; i < vars.length; i++) {
if(!vars[i]) {
continue;
}
var pair = vars[i].split('=');
if(pair.length < 2) {
continue;
}
params[pair[0]] = pair[1];
}
if(params.gid) {
params.gid = parseInt(params.gid, 10);
}
if(!params.hasOwnProperty('pid')) {
return params;
}
params.pid = parseInt(params.pid, 10);
return params;
};
var openPhotoSwipe = function(index, galleryElement, disableAnimation) {
var pswpElement = document.querySelectorAll('.pswp')[0],
gallery,
options,
items;
items = parseThumbnailElements(galleryElement);
// define options (if needed)
options = {
index: index,
// define gallery index (for URL)
galleryUID: galleryElement.getAttribute('data-pswp-uid'),
getThumbBoundsFn: function(index) {
// See Options -> getThumbBoundsFn section of docs for more info
var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
rect = thumbnail.getBoundingClientRect();
return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
},
// history & focus options are disabled on CodePen
// remove these lines in real life:
history: false,
focus: false
};
if(disableAnimation) {
options.showAnimationDuration = 0;
}
// Pass data to PhotoSwipe and initialize it
gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
};
// loop through all gallery elements and bind events
var galleryElements = document.querySelectorAll( gallerySelector );
for(var i = 0, l = galleryElements.length; i < l; i++) {
galleryElements[i].setAttribute('data-pswp-uid', i+1);
galleryElements[i].onclick = onThumbnailsClick;
}
// Parse URL and open gallery if it contains #&pid=3&gid=1
var hashData = photoswipeParseHash();
if(hashData.pid > 0 && hashData.gid > 0) {
openPhotoSwipe( hashData.pid - 1 , galleryElements[ hashData.gid - 1 ], true );
}
};
// execute above function
initPhotoSwipeFromDOM('.my-simple-gallery');
I am stumped. Would really appreciate some guidance to get it working in browser. Thanks in advance. :)
The problem is with when you call the function. You are trying to find the elements before they are rendered to the page. You can call the function at the end of the html document:
<script>
initPhotoSwipeFromDOM('.my-simple-gallery');
</script>
Another way to do it is to add to the onload on body tag:
<body onload="initPhotoSwipeFromDOM('.my-simple-gallery')">
Or set it to the onload function on window:
window.onload="initPhotoSwipeFromDOM('.my-simple-gallery');";
You need to add the link to the js library which i don't see.
<script src="https://code.jquery.com/jquery.min.js"></script>
Maybe i missed it though.

Show images one after one after some interval of time

I am new person in Front End Development and i am facing one major problem is that i have 3 images placed on each others and now i want to move one image so the other image comes up and then it goes and third image comes up after some interval of time.
I want three images on same position in my site but only wants to see these three images one after one after some interval of time.
Please help how i can do this??
May i use marquee property or javascript???
Non-jQuery Option
If you don't want to go down the jquery route, you can try http://www.menucool.com/javascript-image-slider. The setup is just as easy, you just have to make sure that your images are in a div with id of slider and that div has the same dimensions as one of your images.
jQuery Option
The jQuery cycle plugin will help you achieve this. It requires jquery to work but it doesn't need much setting up to create a simple sliple slideshow.
Have a look at the 'super basic' demo:
$(document).ready(function() {
$('.slideshow').cycle({
fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
});
});
It has many options if you want something a bit fancier.
Here you go PURE JavaScript solution:
EDIT I have added image rotation... Check out live example (link below)
<script>
var current = 0;
var rotator_obj = null;
var images_array = new Array();
images_array[0] = "rotator_1";
images_array[1] = "rotator_2";
images_array[2] = "rotator_3";
var rotate_them = setInterval(function(){rotating()},4000);
function rotating(){
rotator_obj = document.getElementById(images_array[current]);
if(current != 0) {
var rotator_obj_pass = document.getElementById(images_array[current-1]);
rotator_obj_pass.style.left = "-320px";
}
else {
rotator_obj.style.left = "-320px";
}
var slideit = setInterval(function(){change_position(rotator_obj)},30);
current++;
if (current == images_array.length+1) {
var rotator_obj_passed = document.getElementById(images_array[current-2]);
rotator_obj_passed.style.left = "-320px";
current = 0;
rotating();
}
}
function change_position(rotator_obj, type) {
var intleft = parseInt(rotator_obj.style.left);
if (intleft != 0) {
rotator_obj.style.left = intleft + 32 + "px";
}
else if (intleft == 0) {
clearInterval(slideit);
}
}
</script>
<style>
#rotate_outer {
position: absolute;
top: 50%;
left: 50%;
width: 320px;
height: 240px;
margin-top: -120px;
margin-left: -160px;
overflow: hidden;
}
#rotate_outer img {
position: absolute;
top: 0px;
left: 0px;
}
</style>
<html>
<head>
</head>
<body onload="rotating();">
<div id="rotate_outer">
<img src="0.jpg" id="rotator_1" style="left: -320px;" />
<img src="1.jpg" id="rotator_2" style="left: -320px;" />
<img src="2.jpg" id="rotator_3" style="left: -320px;" />
</div>
</body>
</html>
And a working example:
http://simplestudio.rs/yard/rotate/rotate.html
If you aim for good transition and effect, I suggest an image slider called "jqFancyTransitions"
<html>
<head>
<script type="text/javascript">
window.onload = function(){
window.displayImgCount = 0;
function cycleImage(){
if (displayImgCount !== 0) {
document.getElementById("img" + displayImgCount).style.display = "none";
}
displayImgCount = displayImgCount === 3 ? 1 : displayImgCount + 1;
document.getElementById("img" + displayImgCount).style.display = "block";
setTimeout(cycleImage, 1000);
}
cycleImage();
}
</script>
</head>
<body>
<img id="img1" src="./img1.png" style="display: none">
<img id="img2" src="./img2.png" style="display: none">
<img id="img3" src="./img3.png" style="display: none">
</body>
</html>​
Fiddle: http://jsfiddle.net/SReject/F7haV/
arrayImageSource= ["Image1","Image2","Image3"];
setInterval(cycle, 2000);
var count = 0;
function cycle()
{
image.src = arrayImageSource[count]
count = (count === 2) ? 0 : count + 1;
}​
Maybe something like this?

Categories

Resources