How to rollover text on images dynamically using javascript/jquery - javascript

I am new to web development but highly fascinated by it. So, basically I am creating a light-box where thumbnails of images will be appear on screen and they will appear bigger in size when user clicks over them. Now, I want when user hovers over the gallery images/thumbnails then some text should appear over the current image with may be some animation or basically mouser-hover should cause some event to happen but I am unable to do it. Text should be added dynamically or may be previously stored in an array or something of that sort. Please have a look at my code and tell me how to modify it in order to achieve such effect and if you know a better and easier way to do so then feel free to share. Thank you so much!!
HTML:
<div class="gallery">
<ul id="images"></ul>
<div class="lightbox">
<div class='limage'>
</div>
<div class='left'>
</div>
<div class='right'>
</div>
<div class='close'>
x
</div>
</div>
</div>
JAVASCRIPT:
var gallery_slider = new Array();
gallery_slider[0] = "im1.jpg";
gallery_slider[1] = "im2.jpg";
gallery_slider[2] = "im3.jpg";
function displayAllImages() {
var i = 0,
len = gallery_slider.length;
for (; i < gallery_slider.length; i++) {
var img = new Image();
img.src = gallery_slider[i];
img.style.width = '200px';
img.style.height = '120px';
img.style.margin = '3px';
img.style.cursor = 'pointer';
document.getElementById('images').appendChild(img);
}
};
$(function() {
displayAllImages();
});
$(function() {
$('img').click(function() {
var hell = (this).src;
display(hell);
});
});
function display(hello) {
$('header').css('display', 'none'); /*for some other purposes*/
$('.limage').html("<img src=" + hello + " >");
$('.lightbox').css("display", "block");
$('.lightbox').fadeIn();
$('.right').click(function() {
var im = new Array();
var x;
var p;
for (x = 0; x < gallery_slider.length; x++) {
im[x] = gallery_slider[x];
}
for (p = 0; p < im.length; p++) {
if (im[p] == hello) {
break;
} else {
continue;
}
}
if (p >= (im.length - 1)) {
p = -1;
}
$('.limage').fadeOut(0);
$('.limage').html("<img src= " + im[p + 1] + ">");
$('.limage').fadeIn(500);
hello = im[p + 1];
});
$('.left').click(function() {
var im = new Array();
var x;
var p;
for (x = 0; x < gallery_slider.length; x++) {
im[x] = gallery_slider[x];
}
for (p = 0; p < im.length; p++) {
if (im[p] == hello) {
break;
} else {
continue;
}
}
if (p == 0) {
p = (im.length);
}
$('.limage').fadeOut(0);
$('.limage').html("<img src= " + im[p - 1] + ">");
$('.limage').fadeIn(500);
hello = im[p - 1];
});
$('.close').click(function() {
$('.lightbox').fadeOut();
$('header').css('display', 'block'); /*for some other purposes*/
});
};
CSS:
.gallery {
width: 100%;
height: 400px;
overflow: hidden;
margin: auto;
}
.gallery ul {
list-style: none;
}
.lightbox {
background-color: rgba(0, 0, 0, 0.3);
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
z-index: 106;
}
.close {
color: #fff;
border: 1px solid #fff;
border-radius: 100px;
background-color: #000;
position: absolute;
top: 10px;
right: 20px;
padding: 10px;
font-family: firstfont;
font-size: 30px;
z-index: 101;
cursor: pointer;
}
.close:hover {
background-color: #ebebeb;
color: #000;
}
.left {
width: 50%;
height: 100%;
position: absolute;
top: 0;
left: 0;
cursor: pointer;
}
.right {
width: 50%;
height: 100%;
position: absolute;
top: 0;
right: 0;
cursor: pointer;
}
.limage {
position: relative;
margin: auto;
top: 17%;
left: 15%;
max-width: 90%;
max-height: 90%;
}
There might be some bugs in coding. Watch out.
This code is working for displaying images as thumbnails as a matrix and as slider in lightbox when clicked upon them. I am not able to figure out how to add hover functionality to initial thumbnails.
Jsfiddle :
http://jsfiddle.net/psd6cbd7/1/

I'd suggest putting a div inside the image div containing the text and then using CSS to hide/show it.
HTML:
<div class="gallery">
<ul id="images"></ul>
<div class="lightbox">
<div class='limage'>
<div class=".caption">Caption here</div>
</div>
<div class='left'>
</div>
<div class='right'>
</div>
<div class='close'>
x
</div>
</div>
</div>
CSS:
.limage { position: relative; }
.caption { display: none; }
.limage:hover .caption { display: block; position: absolute;}

Why you using array to store the images? Anyways, assume that you still using array, below is some example code that you want try:
HTML:
<ul id="images">
</ul>
<!-- assume this is the place that you want to display the caption -->
<div id="caption"></div>
Javascript:
var images = new Array();
images[0] = "p1.png";
images[1] = "p2.png";
images[2] = "p3.png";
images[3] = "p4.png";
var captions = new Array();
captions[0] = "Picture 1";
captions[1] = "Picture 2";
captions[2] = "Picture 3";
captions[3] = "Picture 4";
var x = $("#images");
var y = $("#caption");
const prefix = "image-";
if you are using HTML5:
for (var i = 0; i < images.length; i++) {
x.append("<img class='roll' src='" + images[i] + "' data-caption='" + captions[i] + "'>");
}
$(".roll").mouseover(function(){
//do whatever effect here when mouse over
y.html($(this).attr("data-caption"));
});
If you want to backward compatible:
for (var i = 0; i < images.length; i++) {
x.append("<img id='" + prefix + i + "' class='roll' src='" + images[i] + "'>");
}
$(".roll").mouseover(function(){
//do whatever effect here when mouse over
var index = $(this).attr("id").substring(prefix.length);
y.html(captions[index]);
});
Hope that this will help.

Related

JavaScript itareate over divs and create a new one if doesn't fits

Hello guys I hope you can help me with JavaScript, I'm trying to itarate over some divs, the issue is that when I iterate sometimes a div never change to the other divs, it suppose to be infinite, I will recive thousands of different divs with different height and it should create an other div container in the case it does not fits but I can not achieve it work's, I'm using Vanilla JavaScript because I'm lerning JavaScript Regards.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.big_container{
height: 600px;
width: 150px;
background-color: #f1f1f1;
float: left;
}
.items{
background-color: gray;
height: 50px;
}
.new_container{
margin-bottom: 10px;
height: 300px;
width: 150px;
background-color: red;
float: left;
margin-left: 5px;
}
</style>
</head>
<body>
<div class="big_container">
<div class="items">1</div>
<div class="items">2</div>
<div class="items">3</div>
<div class="items">4</div>
<div class="items">5</div>
<div class="items">6</div>
<div class="items">7</div>
<div class="items">8</div>
<div class="items">9</div>
<div class="items">10</div>
<div class="items">11</div>
<div class="items">12</div>
<div class="items">13</div>
</div>
<div class="new_container">
</div>
</body>
<script>
number = 0
sum = 0
new_container = document.getElementsByClassName('new_container')[number].offsetHeight
divs = document.getElementsByClassName('items')
for ( var i = 0; i < divs.length; i++ ){
sum += this.document.getElementsByClassName( 'items' )[0].offsetHeight
if ( sum <= new_container ){
console.log(sum, "yes")
document.getElementsByClassName("new_container")[number].appendChild( this.document.getElementsByClassName( 'items' )[0] )
} else {
sum = 0
console.log(sum, "NO entra")
nuevo_contenedor = document.createElement('div'); // Creo un contenedor
nuevo_contenedor.className = "new_container";
nuevo_contenedor.setAttribute("style", "background-color: red;");
document.body.appendChild(nuevo_contenedor)
number += + 1
}
}
</script>
</html>
I really apreciate a hand.
I know that I'm late, but there is my approach how this can be done.
// generate items with different height
function generateItems(count) {
const arr = [];
for (let i = 0; i < count; i++) {
const div = document.createElement("DIV");
const height = Math.floor((Math.random() * 100) + 10);
div.setAttribute("style", `height: ${height}px`);
div.setAttribute("class", "items");
const t = document.createTextNode(i + 1);
div.appendChild(t);
arr.push(div);
}
return arr;
}
function createNewContainer(height) {
const new_container = document.createElement("DIV")
new_container.setAttribute("class", "new_container");
new_container.setAttribute("style", `height: ${height}px`)
document.body.appendChild(new_container);
return new_container;
}
function breakFrom(sourceContainerId, newContainerHeight) {
const srcContainer = document.getElementById(sourceContainerId);
const items = srcContainer.childNodes;
let new_container = createNewContainer(newContainerHeight);
let sumHeight = 0;
for (let i = 0; i < items.length; i++) {
let item = items[i];
if (item.offsetHeight > newContainerHeight) {
// stop!!! this item too big to fill into new container
throw new Error("Item too big.");
}
if (sumHeight + item.offsetHeight < newContainerHeight) {
// add item to new container
sumHeight += item.offsetHeight;
new_container.appendChild(item.cloneNode(true));
} else {
// create new container
new_container = createNewContainer(newContainerHeight);
new_container.appendChild(item.cloneNode(true));
// don't forget to set sumHeight)
sumHeight = item.offsetHeight;
}
}
// if you want to remove items from big_container
// for (let i = items.length - 1; i >= 0; i--) {
// srcContainer.removeChild(items[i]);
// }
}
// create big container with divs
const big_container = document.getElementById("big_container");
const items = generateItems(13);
items.forEach((div, index) => {
big_container.appendChild(div);
});
breakFrom("big_container", 300);
#big_container {
width: 150px;
background-color: #f1f1f1;
float: left;
}
.items {
background-color: gray;
border: 1px solid #000000;
text-align: center;
}
.new_container {
margin-bottom: 10px;
height: 300px;
width: 150px;
background-color: red;
border: 1px solid red;
float: left;
margin-left: 5px;
}
<div id="big_container"></div>
This example gives you the ability to play with divs of random height. Hope, this will help you.

How to change class and text of one tag by clicking on another tag?

I don't know how to describe this without making it more complicated.
So look at the result of the code and click on the first link with "Show", then the second one and third one.
When the second link is clicked, first one closes but text remains "Hide" and i want it to change to "Show".
So, when clicking a link, detect if any other link has text "Hide" and change it to "Show".
And please no jQuery...
document.getElementsByClassName("show")[0].onclick = function() {
var x = document.getElementsByClassName("hide")[0];
var y = document.getElementsByClassName("show")[0];
if (x.classList.contains("visible")) {
x.classList.remove("visible");
y.textContent = "Show";
} else {
closeOther();
x.classList.add("visible");
y.textContent = "Hide";
}
};
document.getElementsByClassName("show")[1].onclick = function() {
var x = document.getElementsByClassName("hide")[1];
var y = document.getElementsByClassName("show")[1];
if (x.classList.contains("visible")) {
x.classList.remove("visible");
y.textContent = "Show";
} else {
closeOther();
x.classList.add("visible");
y.textContent = "Hide";
}
};
document.getElementsByClassName("show")[2].onclick = function() {
var x = document.getElementsByClassName("hide")[2];
var y = document.getElementsByClassName("show")[2];
if (x.classList.contains("visible")) {
x.classList.remove("visible");
y.textContent = "Show";
} else {
closeOther();
x.classList.add("visible");
y.textContent = "Hide";
}
};
function closeOther() {
var visible = document.querySelectorAll(".visible"),
i, l = visible.length;
for (i = 0; i < l; ++i) {
visible[i].classList.remove("visible");
}
}
.style {
background-color: yellow;
width: 200px;
height: 200px;
display: inline-block;
}
.hide {
background-color: red;
width: 50px;
height: 50px;
display: none;
position: relative;
top: 50px;
left: 50px;
}
.hide.visible {
display: block;
}
<div class="style">
Show
<div class="hide">
</div>
</div>
<div class="style">
Show
<div class="hide">
</div>
</div>
<div class="style">
Show
<div class="hide">
</div>
</div>
I tried to write a solution which didn't use any javascript at all and worked using CSS alone. I couldn't get it to work though - CSS can identify focus but it can't identify blur (ie. when focus has just been removed).
So here is a solution which uses javascript and the classList API, instead:
var divs = document.getElementsByTagName('div');
function toggleFocus() {
for (var i = 0; i < divs.length; i++) {
if (divs[i] === this) continue;
divs[i].classList.add('show');
divs[i].classList.remove('hide');
}
this.classList.toggle('show');
this.classList.toggle('hide');
}
for (let i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', toggleFocus, false);
}
div {
display: inline-block;
position: relative;
width: 140px;
height: 140px;
background-color: rgb(255,255,0);
}
.show::before {
content: 'show';
}
.hide::before {
content: 'hide';
}
div::before {
color: rgb(0,0,255);
text-decoration: underline;
cursor: pointer;
}
.hide::after {
content: '';
position: absolute;
top: 40px;
left: 40px;
width: 50px;
height: 50px;
background-color: rgb(255,0,0);
}
<div class="show"></div>
<div class="show"></div>
<div class="show"></div>
Like this?
Just added following to closeOther():
visible = document.querySelectorAll(".show"),
i, l = visible.length;
for (i = 0; i < l; ++i) {
visible[i].textContent="Show";
}

JavaScript: Problems in Snakes and Ladders Game [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am new to JavaScript. I am making Snakes and Ladders game. I am facing some problems on the code.
First I can not store the current position of the player so I can count the next destination.
The dice starts with 1 at the beginning of the game and this causes the player to start from the second cell.
The big snake and ladder divs displayed onto the board are not auto fit to the size of the board.
Here is the code I wrote so far Snakes and Ladder Game
var gameBoard = {
createBoard: function(dimension, mount) {
var mount = document.querySelector(mount);
if (!dimension || isNaN(dimension) || !parseInt(dimension, 10)) {
return false;
} else {
dimension = typeof dimension === 'string' ? parseInt(dimension, 10) : dimension;
var table = document.createElement('table'),
row = document.createElement('tr'),
cell = document.createElement('td'),
rowClone,
cellClone;
var output;
for (var r = 0; r < dimension; r++) {
rowClone = row.cloneNode(true);
table.appendChild(rowClone);
for (var c = 0; c < dimension; c++) {
cellClone = cell.cloneNode(true);
rowClone.appendChild(cellClone);
}
}
mount.appendChild(table);
output = gameBoard.enumerateBoard(table);
}
return output;
},
enumerateBoard: function(board) {
var rows = board.getElementsByTagName('tr'),
text = document.createTextNode(''),
rowCounter = 1,
size = rows.length,
cells,
cellsLength,
cellNumber,
odd = false,
control = 0;
for (var r = size - 1; r >= 0; r--) {
cells = rows[r].getElementsByTagName('td');
cellsLength = cells.length;
rows[r].className = r % 2 == 0 ? 'even' : 'odd';
odd = ++control % 2 == 0 ? true : false;
size = rows.length;
for (var i = 0; i < cellsLength; i++) {
if (odd == true) {
cellNumber = --size + rowCounter - i;
} else {
cellNumber = rowCounter;
}
cells[i].className = i % 2 == 0 ? 'even' : 'odd';
cells[i].id = cellNumber;
cells[i].appendChild(text.cloneNode());
cells[i].firstChild.nodeValue = cellNumber;
rowCounter++;
}
}
var lastRow = rows[0].getElementsByTagName('td');
lastRow[0].id = '100';
var firstRow = rows[9].getElementsByTagName('td');
firstRow[0].id = '1';
return gameBoard;
}
};
gameBoard.createBoard(10, "#grid");
function intialPosition() {
$("#1").append($("#player1"));
$("#1").append($("#player2"));
var currentPosition = parseInt($("#1").attr('id'));
return currentPosition;
}
var w = intialPosition();
var face1 = new Image()
face1.src = "http://s19.postimg.org/fa5etrfy7/image.gif"
var face2 = new Image()
face2.src = "http://s19.postimg.org/qb0jys873/image.gif"
var face3 = new Image()
face3.src = "http://s19.postimg.org/fpgoms1vj/image.gif"
var face4 = new Image()
face4.src = "http://s19.postimg.org/xgsb18ha7/image.gif"
var face5 = new Image()
face5.src = "http://s19.postimg.org/lsy96os5b/image.gif"
var face6 = new Image()
face6.src = "http://s19.postimg.org/4gxwl8ynz/image.gif"
function rollDice() {
var randomdice = Math.floor(Math.random() * 6) + 1;
document.images["mydice"].src = eval("face" + randomdice + ".src")
if (randomdice == 6) {
alert('Congratulations! You got 6! Roll the dice again');
}
return randomdice;
}
var random1 = rollDice();
var destination = w + random1;
function move() {
$('#' + destination).append($("#player1"));
var x = parseInt($('#' + destination).attr('id'));
var random = rollDice();
destination = x + random;
//alert(x);
return destination;
}
$(document).ready(function() {
//$('#' + destination).delay(100).fadeOut().fadeIn('slow');
$('#' + destination).fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
});
var next = move();
/*body {
background-image: url('snakesandladder2.png');
background-repeat: no-repeat;
background-size: 100%;
background-color: #4f96cb;
}*/
#game {
width: 80%;
margin-left: auto;
margin-right: auto;
display: table;
}
#gameBoardSection {
border: 3px inset #0FF;
border-radius: 10px;
width: 65%;
display: table-cell;
}
table {
width: 100%;
}
td {
border-radius: 10px;
width: 60px;
height: 60px;
line-height: normal;
vertical-align: bottom;
text-align: left;
border: 0px solid #FFFFFF;
position: relative;
}
table tr:nth-child(odd) td:nth-child(even),
table tr:nth-child(even) td:nth-child(odd) {
background-color: PowderBlue;
}
table tr:nth-child(even) td:nth-child(even),
table tr:nth-child(odd) td:nth-child(odd) {
background-color: SkyBlue;
}
#100 {
background-image: url('http://s19.postimg.org/ceioc1g8v/rotstar2_e0.gif');
background-repeat: no-repeat;
background-size: 100%;
}
#ladder {
position: absolute;
top: 300px;
left: 470px;
-webkit-transform: rotate(30deg);
z-index: 1;
opacity: 0.7;
}
#bigSnake {
position: absolute;
top: 20px;
left: 200px;
opacity: 0.7;
z-index: 1;
}
#diceAndPlayerSection {
background-color: lightpink;
border: 1px;
border-style: solid;
display: table-cell;
border-radius: 10px;
border: 3px inset #0FF;
width: 35%;
}
<body>
<div id="game">
<div id="gameBoardSection">
<div id="grid"></div>
<div id="ladder">
<img src="http://s19.postimg.org/otai9he2n/oie_e_RDOY2iqd5o_Q.gif" />
</div>
<div id="bigSnake">
<img src="http://s19.postimg.org/hrcknaagz/oie_485727s_RN4_KKBG.png" />
</div>
<div id="player1" style="position:absolute; top:10px; left:10px;">
<img src="http://s19.postimg.org/t108l496n/human_Piece.png" />
</div>
<div id="player2" style="position:absolute; top:15px; left:5px;">
<img src="http://s19.postimg.org/l6zmzq1dr/computer_Piece.png" />
</div>
</div>
<div id="diceAndPlayerSection">
<div id="reset">
<button type="button" name="newGame" onClick="gameVM.newGame();">New Game</button>
</div>
<div>
<button type="button" name="reset" onClick="gameVM.defaultSetup()">Reset</button>
</div>
<div>
<button type="button" name="addPlayer">Add Player</button>
</div>
<div id="diceSection">
<img src="d1.gif" name="mydice" onclick="rollDice()" style="background-color: white;">
</div>
</div>
</div>
</body>
Can anyone help me on that? Thanks in advance
To store the user current position , maintain the separate variable for storing the destination of diff player.
To start the play from the 1 , remove intialPosition() and make var w=0 , so once you call the rolldice() , it will start from 0.
In order to auto fit based on the change in screen size , use the bootstrap div which can auto fit the size of the div. Here is the link for it http://getbootstrap.com/css/#grid

Semi-fixed text in a scrolling container

I've got a bunch of horizontal boxes containing text. The boxes are all in a horizontally scrolling container:
// generate some random data
var model = {
leftEdge: ko.observable(0)
};
model.rows = populateArray(10 + randInt(20), randRow);
ko.applyBindings(model);
$(function() {
$('.slide').on('scroll', function() {
model.leftEdge(this.scrollLeft);
})
})
function randRow() {
var events = populateArray(50 + randInt(100), randEvent);
var left = randInt(1000);
events.forEach(function(event) {
event.left = left;
left += 10 + event.width + randInt(1000);
});
return {
events: events
}
}
function randEvent() {
var word = randWord()
var width = 50 + Math.max(8 * word.length, randInt(200));
var event = {
left: 0,
width: width,
label: word
};
event.offset = ko.computed(function() {
// reposition the text to stay
// * within its container
// * fully on-screen (if possible)
var leftEdge = model.leftEdge();
return Math.max(0, Math.min(
leftEdge - event.left,
event.width - 8 * event.label.length
));
});
return event;
}
function randWord() {
var n = 2 + randInt(5);
var ret = "";
while (n-- > 0) {
ret += randElt("rmhntsk");
ret += randElt("aeiou");
}
return ret;
}
function randElt(arr) {
return arr[randInt(arr.length)];
}
function populateArray(n, populate) {
var arr = new Array(n);
for (var i = 0; i < n; i++) {
arr[i] = populate();
}
return arr;
}
function randInt(n) {
return Math.floor(Math.random() * n);
}
.slide {
max-width: 100%;
overflow: auto;
border: 5px solid black;
}
.row {
position: relative;
height: 25px;
}
.event {
position: absolute;
top: 2.5px;
border: 1px solid black;
padding: 2px;
background: #cdffff;
font-size: 14px;
font-family: monospace;
}
.event > span {
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div class="slide" data-bind="foreach: rows">
<div class="row" data-bind="foreach: events">
<div class="event" data-bind="style: { left: left+'px', width: width+'px' }"><span data-bind="text:label, style: { left: offset() + 'px' }"></div>
</div>
</div>
What I'd like to do is as the user scrolls from left-to-right, reposition the text within each box that partially overlaps the left border of the visible window to keep the text as visible as possible.
Currently I'm doing this by manually repositioning each item of text.
Is there a cleaner way to do this using CSS?
A friend helped me come up with this solution.
In English, the idea is to add an overlay to each row that is positioned relatively to the frame of the scrolling box, rather than the contents.
Then we can place a label for any box that overlaps the left edge in this overlay and it will appear to smoothly move as the box underneath it scrolls.
// generate some random data
var model = {
leftEdge: ko.observable(0),
};
model.rows = populateArray(10 + randInt(20), randRow);
model.width = Math.max.apply(Math, $.map(model.rows, function(row) {
return row.width
}));
ko.applyBindings(model);
$(function() {
$('.slide').on('scroll', function() {
model.leftEdge(this.scrollLeft);
})
})
function randRow() {
var events = populateArray(50 + randInt(100), randEvent);
var left = randInt(1000);
events.forEach(function(event) {
event.left = left;
left += 10 + event.width + randInt(1000);
});
return {
events: events,
width: left
}
}
function randEvent() {
var word = randWord()
var width = 50 + Math.max(8 * word.length, randInt(200));
var event = {
width: width,
label: word,
};
event.tense = ko.computed(function() {
// reposition the text to stay#
// * within its container
// * fully on-screen (if possible)
var leftEdge = model.leftEdge();
return ['future', 'present', 'past'][
(leftEdge >= event.left) +
(leftEdge > event.left + event.width - 8 * event.label.length)
];
});
return event;
}
function randWord() {
var n = 2 + randInt(5);
var ret = "";
while (n-- > 0) {
ret += randElt("rmhntsk");
ret += randElt("aeiou");
}
return ret;
}
function randElt(arr) {
return arr[randInt(arr.length)];
}
function populateArray(n, populate) {
var arr = new Array(n);
for (var i = 0; i < n; i++) {
arr[i] = populate();
}
return arr;
}
function randInt(n) {
return Math.floor(Math.random() * n);
}
.wrapper {
position: relative;
border: 5px solid black;
font-size: 14px;
font-family: monospace;
}
.slide {
max-width: 100%;
overflow: auto;
}
.slide > * {
height: 25px;
}
.overlay {
position: absolute;
width: 100%;
left: 0;
}
.overlay .past {
display: none
}
.overlay .present {
position: absolute;
z-index: 1;
top: 5.5px;
left 0;
}
.overlay .future {
display: none
}
.row {
position: relative;
}
.event {
position: absolute;
top: 2.5px;
border: 1px solid black;
padding: 2px;
background: #cdffff;
height: 14px;
}
.event .past {
float: right;
}
.event .present {
display: none;
}
.event .future {
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div class="wrapper">
<div class="slide" data-bind="foreach: rows, style: { width: width + 'px' }">
<div class="overlay" data-bind="foreach: events">
<span data-bind="text:label, css: tense"></span>
</div>
<div class="row" data-bind="foreach: events">
<div class="event" data-bind="style: { left: left+'px', width: width+'px' }"><span data-bind="text:label, css: tense"></div>
</div>
</div></div>
This doesn't result in less javascript, but it does result in more efficient javascript, as class changes happen much less often than offset changes, so fewer updates to DOM elements are required.
You can avoid processing every "event" (in the above example) by doing some pre-partitioning of the horizontal space, and only updating events in the relevant partition.

How to build simple jQuery image slider with sliding or opacity effect?

Some of us might not want to use ready plugins because of their high sizes and possibilty of creating conflicts with current javascript.
I was using light slider plugins before but when customer gives modular revise, it became really hard to manipulate. Then I aim to build mine for customising it easily. I believe sliders shouldn't be that complex to build from beginning.
What is a simple and clean way to build jQuery image slider?
Before inspecting examples, you should know two jQuery functions which i used most.
index() returns value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
eq() selects of an element based on its position (index value).
Basicly i take selected trigger element's index value and match this value on images with eq method.
- FadeIn / FadeOut effect.
- Sliding effect.
- alternate Mousewheel response.
​html sample:
<ul class="images">
<li>
<img src="images/1.jpg" alt="1" />
</li>
<li>
<img src="images/2.jpg" alt="2" />
</li>
...
</ul>
<ul class="triggers">
<li>1</li>
<li>2</li>
...
</ul>
<span class="control prev">Prev</span>
<span class="control next">Next</span>
OPACITY EFFECT: jsFiddle.
css trick: overlapping images with position:absolute
ul.images { position:relative; }
ul.images li { position:absolute; }
jQuery:
var target;
var triggers = $('ul.triggers li');
var images = $('ul.images li');
var lastElem = triggers.length-1;
triggers.first().addClass('active');
images.hide().first().show();
function sliderResponse(target) {
images.fadeOut(300).eq(target).fadeIn(300);
triggers.removeClass('active').eq(target).addClass('active');
}
SLIDING EFFECT: jsFiddle.
css trick: with double wrapper and use child as mask
.mask { float:left; margin:40px; width:270px; height:266px; overflow:hidden; }
ul.images { position:relative; top:0px;left:0px; }
/* this width must be total of the images, it comes from jquery */
ul.images li { float:left; }
jQuery:
var target;
var triggers = $('ul.triggers li');
var images = $('ul.images li');
var lastElem = triggers.length-1;
var mask = $('.mask ul.images');
var imgWidth = images.width();
triggers.first().addClass('active');
mask.css('width', imgWidth*(lastElem+1) +'px');
function sliderResponse(target) {
mask.stop(true,false).animate({'left':'-'+ imgWidth*target +'px'},300);
triggers.removeClass('active').eq(target).addClass('active');
}
Common jQuery response for both slider:
( triggers + next/prev click and timing )
triggers.click(function() {
if ( !$(this).hasClass('active') ) {
target = $(this).index();
sliderResponse(target);
resetTiming();
}
});
$('.next').click(function() {
target = $('ul.triggers li.active').index();
target === lastElem ? target = 0 : target = target+1;
sliderResponse(target);
resetTiming();
});
$('.prev').click(function() {
target = $('ul.triggers li.active').index();
lastElem = triggers.length-1;
target === 0 ? target = lastElem : target = target-1;
sliderResponse(target);
resetTiming();
});
function sliderTiming() {
target = $('ul.triggers li.active').index();
target === lastElem ? target = 0 : target = target+1;
sliderResponse(target);
}
var timingRun = setInterval(function() { sliderTiming(); },5000);
function resetTiming() {
clearInterval(timingRun);
timingRun = setInterval(function() { sliderTiming(); },5000);
}
Here is a simple and easy to understand code for Creating image slideshow using JavaScript without using Jquery.
<script language="JavaScript">
var i = 0; var path = new Array();
// LIST OF IMAGES
path[0] = "image_1.gif";
path[1] = "image_2.gif";
path[2] = "image_3.gif";
function swapImage() { document.slide.src = path[i];
if(i < path.length - 1) i++;
else i = 0; setTimeout("swapImage()",3000);
} window.onload=swapImage;
</script>
<img height="200" name="slide" src="image_1.gif" width="400" />
I have recently created a solution with a gallery of images and a slider that apears when an image is clicked.
Take a look at the code here: GitHub Code
And a live example here: Code Example
var CreateGallery = function(parameters) {
var self = this;
this.galleryImages = [];
this.galleryImagesSrcs = [];
this.galleryImagesNum = 0;
this.counter;
this.galleryTitle = parameters.galleryTitle != undefined ? parameters.galleryTitle : 'Gallery image';
this.maxMobileWidth = parameters.maxMobileWidth != undefined ? parameters.maxMobileWidth : 768;
this.numMobileImg = parameters.numMobileImg != undefined ? parameters.numMobileImg : 2;
this.maxTabletWidth = parameters.maxTabletWidth != undefined ? parameters.maxTabletWidth : 1024;
this.numTabletImg = parameters.numTabletImg != undefined ? parameters.numTabletImg : 3;
this.addModalGallery = function(gallerySelf = self){
var $div = $(document.createElement('div')).attr({
'id': 'modal-gallery'
}).append($(document.createElement('div')).attr({
'class': 'header'
}).append($(document.createElement('button')).attr({
'class': 'close-button',
'type': 'button'
}).html('×')
).append($(document.createElement('h2')).text(gallerySelf.galleryTitle))
).append($(document.createElement('div')).attr({
'class': 'text-center'
}).append($(document.createElement('img')).attr({
'id': 'gallery-img'
})
).append($(document.createElement('button')).attr({
'class': 'prev-button',
'type': 'button'
}).html('◄')
).append($(document.createElement('button')).attr({
'class': 'next-button',
'type': 'button'
}).html('►')
)
);
parameters.element.after($div);
};
$(document).on('click', 'button.prev-button', {self: self}, function() {
var $currImg = self.counter >= 1 ? self.galleryImages[--self.counter] : self.galleryImages[self.counter];
var $currHash = self.galleryImagesSrcs[self.counter];
var $src = $currImg.src;
window.location.hash = $currHash;
$('img#gallery-img').attr('src', $src);
$('div#modal-gallery h2').text(self.galleryTitle + ' ' + (self.counter + 1));
});
$(document).on('click', 'button.next-button', {self: self}, function() {
var $currImg = self.counter < (self.galleryImagesNum - 1) ? self.galleryImages[++self.counter] : self.galleryImages[self.counter];
var $currHash = self.galleryImagesSrcs[self.counter];
var $src = $currImg.src;
window.location.hash = $currHash;
$('img#gallery-img').attr('src', $src);
$('div#modal-gallery h2').text(self.galleryTitle + ' ' + (self.counter + 1));
});
$(document).on('click', 'div#modal-gallery button.close-button', function() {
$('#modal-gallery').css('position', 'relative');
$('#modal-gallery').hide();
$('body').css('overflow', 'visible');
});
parameters.element.find('a').on('click', {self: self}, function(event) {
event.preventDefault();
$('#modal-gallery').css('position', 'fixed');
$('#modal-gallery').show();
$('body').css('overflow', 'hidden');
var $currHash = this.hash.substr(1);
self.counter = self.galleryImagesSrcs.indexOf($currHash);
var $src = $currHash;
window.location.hash = $currHash;
$('img#gallery-img').attr('src', $src);
$('div#modal-gallery h2').text(self.galleryTitle + ' ' + (self.counter + 1));
});
this.sizeGallery = function(gallerySelf = self) {
var $modalGallery = $(document).find("div#modal-gallery");
if($modalGallery.length <= 0) {
this.addModalGallery();
}
var $windowWidth = $(window).width();
var $parentWidth = parameters.element.width();
var $thumbnailHref = parameters.element.find('img:first').attr('src');
if($windowWidth < gallerySelf.maxMobileWidth) {
var percentMobile = Math.floor(100 / gallerySelf.numMobileImg);
var emMobile = 0;
var pxMobile = 2;
// var emMobile = gallerySelf.numMobileImg * 0.4;
// var pxMobile = gallerySelf.numMobileImg * 2;
parameters.element.find('img').css('width', 'calc('+percentMobile+'% - '+emMobile+'em - '+pxMobile+'px)');
} else if($windowWidth < gallerySelf.maxTabletWidth) {
var percentTablet = Math.floor(100 / gallerySelf.numTabletImg);
var emTablet = 0;
var pxTablet = 2;
// var emTablet = gallerySelf.numMobileImg * 0.4;
// var pxTablet = gallerySelf.numMobileImg * 2;
parameters.element.find('img').css('width', 'calc('+percentTablet+'% - '+emTablet+'em - '+pxTablet+'px)');
} else {
var $thumbImg = new Image();
$thumbImg.src = $thumbnailHref;
$thumbImg.onload = function() {
var $thumbnailWidth = this.width;
if($parentWidth > 0 && $thumbnailWidth > 0) {
parameters.element.find('img').css('width', (Math.ceil($thumbnailWidth * 100 / $parentWidth))+'%');
}
};
}
};
this.startGallery = function(gallerySelf = self) {
parameters.element.find('a').each(function(index, el) {
var $currHash = el.hash.substr(1);
var $img = new Image();
$img.src = $currHash;
gallerySelf.galleryImages.push($img);
gallerySelf.galleryImagesSrcs.push($currHash);
});
this.galleryImagesNum = this.galleryImages.length;
};
this.sizeGallery();
this.startGallery();
};
var myGallery;
$(window).on('load', function() {
myGallery = new CreateGallery({
element: $('#div-gallery'),
maxMobileWidth: 768,
numMobileImg: 2,
maxTabletWidth: 1024,
numTabletImg: 3
});
});
$(window).on('resize', function() {
myGallery.sizeGallery();
});
#div-gallery {
text-align: center;
}
#div-gallery img {
margin-right: auto;
margin-left: auto;
}
div#modal-gallery {
top: 0;
left: 0;
width: 100%;
max-width: none;
height: 100vh;
min-height: 100vh;
margin-left: 0;
border: 0;
border-radius: 0;
z-index: 1006;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
display: none;
background-color: #fefefe;
position: relative;
margin-right: auto;
overflow-y: auto;
padding: 0;
}
div#modal-gallery div.header {
position: relative;
}
div#modal-gallery div.header h2 {
margin-left: 1rem;
}
div#modal-gallery div.header button.close-button {
position: absolute;
top: calc(50% - 1em);
right: 1rem;
}
div#modal-gallery img {
display: block;
max-width: 98%;
max-height: calc(100vh - 5em);
margin-right: auto;
margin-left: auto;
}
div#modal-gallery div.text-center {
position: relative;
}
button.close-button {
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 20px;
font-weight: 400;
line-height: 1.42857143;
text-align: center;
white-space: nowrap;
vertical-align: middle;
-ms-touch-action: manipulation;
touch-action: manipulation;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
color: #333;
background-color: #fff;
border-color: #ccc;
}
button.close-button:hover, button.close-button:focus {
background-color: #ddd;
}
button.next-button:hover, button.prev-button:hover, button.next-button:focus, button.prev-button:focus {
color: #fff;
text-decoration: none;
filter: alpha(opacity=90);
outline: 0;
opacity: .9;
}
button.next-button, button.prev-button {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 15%;
font-size: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0,0,0,.6);
background-color: rgba(0,0,0,0);
filter: alpha(opacity=50);
opacity: .5;
border: none;
}
button.next-button {
right: 0;
left: auto;
background-image: -webkit-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);
background-image: -o-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);
background-image: -webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.0001)),to(rgba(0,0,0,.5)));
background-image: linear-gradient(to right,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
background-repeat: repeat-x;
}
button.prev-button {
background-image: -webkit-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);
background-image: -o-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);
background-image: -webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.5)),to(rgba(0,0,0,.0001)));
background-image: linear-gradient(to right,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
background-repeat: repeat-x;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="div-gallery">
<img src="http://placehold.it/300x300/ff0000/000000?text=Gallery+image+1" alt="">
<img src="http://placehold.it/300x300/ff4000/000000?text=Gallery+image+2" alt="">
<img src="http://placehold.it/300x300/ff8000/000000?text=Gallery+image+3" alt="">
<img src="http://placehold.it/300x300/ffbf00/000000?text=Gallery+image+4" alt="">
<img src="http://placehold.it/300x300/ffff00/000000?text=Gallery+image+5" alt="">
<img src="http://placehold.it/300x300/bfff00/000000?text=Gallery+image+6" alt="">
<img src="http://placehold.it/300x300/80ff00/000000?text=Gallery+image+7" alt="">
<img src="http://placehold.it/300x300/40ff00/000000?text=Gallery+image+8" alt="">
<img src="http://placehold.it/300x300/00ff00/000000?text=Gallery+image+9" alt="">
<img src="http://placehold.it/300x300/00ff40/000000?text=Gallery+image+10" alt="">
<img src="http://placehold.it/300x300/00ff80/000000?text=Gallery+image+11" alt="">
<img src="http://placehold.it/300x300/00ffbf/000000?text=Gallery+image+12" alt="">
<img src="http://placehold.it/300x300/00ffff/000000?text=Gallery+image+13" alt="">
<img src="http://placehold.it/300x300/00bfff/000000?text=Gallery+image+14" alt="">
<img src="http://placehold.it/300x300/0080ff/000000?text=Gallery+image+15" alt="">
<img src="http://placehold.it/300x300/0040ff/000000?text=Gallery+image+16" alt="">
</div>
Checkout this whole bunch of code to build simple jquery image slider. Copy and save this file to local machine and test it. You can modify it according to your requirement.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
var current_img = 1;
var i;
$(document).ready(function(){
var imgs = $("#image").find("img");
function show_img(){
for (i = 1; i < imgs.length+1; i++) {
if(i == current_img){
$(imgs[i-1]).show();
}else{
$(imgs[i-1]).hide()
}
}
}
$("#prev").click(function(){
if(current_img == 1){
current_img = imgs.length;
}else{
current_img = current_img - 1
}
show_img();
});
$("#next").click(function(){
if(current_img == imgs.length){
current_img = 1;
}else{
current_img = current_img + 1
}
show_img();
});
});
</script>
</head>
<body>
<div style="margin-top: 100px;"></div>
<div class="container">
<div class="col-sm-3">
<button type="button" id="prev" class="btn">Previous</button>
</div>
<div class="col-sm-6">
<div id="image">
<img src="https://www.w3schools.com/html/pulpitrock.jpg" alt="image1">
<img src="https://www.w3schools.com/cSS/img_forest.jpg" alt="image2" hidden="true" style="max-width: 500px;">
<img src="https://www.w3schools.com/html/img_chania.jpg" alt="image3" hidden="true">
</div>
</div>
<div class="col-sm-3">
<button type="button" id="next" class="btn">Next</button>
</div>
</div>
</body>
</html>
I have written a tutorial on creating a slideshow, The tutorial page
In case the link becomes invalid I have included the code in my answer below.
the html:
<div id="slideShow">
<div id="slideShowWindow">
<div class="slide">
<img src="”img1.png”/">
<div class="slideText">
<h2>The Slide Title</h2>
<p>This is the slide text</p>
</div> <!-- </slideText> -->
</div> <!-- </slide> repeat as many times as needed -->
</div> <!-- </slideShowWindow> -->
</div> <!-- </slideshow> -->
css:
img {
display: block;
width: 100%;
height: auto;
}
p{
background:none;
color:#ffffff;
}
#slideShow #slideShowWindow {
width: 650px;
height: 450px;
margin: 0;
padding: 0;
position: relative;
overflow:hidden;
margin-left: auto;
margin-right:auto;
}
#slideShow #slideShowWindow .slide {
margin: 0;
padding: 0;
width: 650px;
height: 450px;
float: left;
position: relative;
margin-left:auto;
margin-right: auto;
}
#slideshow #slideshowWindow .slide, .slideText {
position:absolute;
bottom:18px;
left:0;
width:100%;
height:auto;
margin:0;
padding:0;
color:#ffffff;
font-family:Myriad Pro, Arial, Helvetica, sans-serif;
}
.slideText {
background: rgba(128, 128, 128, 0.49);
}
#slideshow #slideshowWindow .slide .slideText h2,
#slideshow #slideshowWindow .slide .slideText p {
margin:10px;
padding:15px;
}
.slideNav {
display: block;
text-indent: -10000px;
position: absolute;
cursor: pointer;
}
#leftNav {
left: 0;
bottom: 0;
width: 48px;
height: 48px;
background-image: url("../Images/plus_add_minus.png");
background-repeat: no-repeat;
z-index: 10;
}
#rightNav {
right: 0;
bottom: 0;
width: 48px;
height: 48px;
background-image: url("../Images/plus_add_green.png");
background-repeat: no-repeat;
z-index: 10; }
jQuery:
$(document).ready(function () {
var currentPosition = 0;
var slideWidth = 650;
var slides = $('.slide');
var numberOfSlides = slides.length;
var slideShowInterval;
var speed = 3000;
//Assign a timer, so it will run periodically
slideShowInterval = setInterval(changePosition, speed);
slides.wrapAll('<div id="slidesHolder"></div>');
slides.css({ 'float': 'left' });
//set #slidesHolder width equal to the total width of all the slides
$('#slidesHolder').css('width', slideWidth * numberOfSlides);
$('#slideShowWindow')
.prepend('<span class="slideNav" id="leftNav">Move Left</span>')
.append('<span class="slideNav" id="rightNav">Move Right</span>');
manageNav(currentPosition);
//tell the buttons what to do when clicked
$('.slideNav').bind('click', function () {
//determine new position
currentPosition = ($(this).attr('id') === 'rightNav')
? currentPosition + 1 : currentPosition - 1;
//hide/show controls
manageNav(currentPosition);
clearInterval(slideShowInterval);
slideShowInterval = setInterval(changePosition, speed);
moveSlide();
});
function manageNav(position) {
//hide left arrow if position is first slide
if (position === 0) {
$('#leftNav').hide();
}
else {
$('#leftNav').show();
}
//hide right arrow is slide position is last slide
if (position === numberOfSlides - 1) {
$('#rightNav').hide();
}
else {
$('#rightNav').show();
}
}
//changePosition: this is called when the slide is moved by the timer and NOT when the next or previous buttons are clicked
function changePosition() {
if (currentPosition === numberOfSlides - 1) {
currentPosition = 0;
manageNav(currentPosition);
} else {
currentPosition++;
manageNav(currentPosition);
}
moveSlide();
}
//moveSlide: this function moves the slide
function moveSlide() {
$('#slidesHolder').animate({ 'marginLeft': slideWidth * (-currentPosition) });
}
});

Categories

Resources