Prevent image slideshow grows more than container cell - javascript

I'm making a little html-jquery program that generate dynamically a table where on each cell there are an slideshow. The slideshow get the images that you select from a folder inside your computer.
The problem is that when I select the folder the slideshow gets the height to 100vh for each cell with slideshow. I can't understand how prevent that the slideshow grows more than the containing cell.
HTML
<body style="height:100vh;">
<div class="row">
<div class="container-fluid">
Rows: <input id="sRows" type="number" name="" value="2">
Columns: <input id="sCol" type="number" name="" value="2">
<button id="btnGen" type="button" name="button">Generate!</button>
</div>
</div>
<div id="slideshowContiner" class="w3-table-all" >
</div>
</body>
CSS
#slideshowContiner {
table-layout: fixed;
height: 100%;
}
.slider{
max-width:100%;
max-height: 100%;
}
.mySlide{
width:100%;
height:auto;
}
For Javascript code maybe is too long for read, finally the created structure is, inside the #slideshowContiner is something like that:
<div id="slideshowContiner" class="w3-table-all">
<tr></tr>
<td style="background-color:#6a833c">
<input webkitdirectory="" mozdirectory="" msdirectory="" odirectory="" directory="" multiple="" type="file" name="file">
<div class="w3-content w3-section slider" style="">
<img class="mySlide" style="display: none;" src="blob:null/">
<img class="mySlide" style="display: none;" src="blob:null/">
<img class="mySlide" style="display: none;" src="blob:null/">
</div>
</td>
</div>
Jquery (TL:DR;)
$( document ).ready(function() {
var randomColor = function (){
return '#'+ ('000000' + Math.floor(Math.random()*16777215).toString(16)).slice(-6);
}
var sliders = []
var myIndex = 0;
function carousel() {
var i;
var slides = elem.children( ".mySlide" ).css("display", "none")
console.log(slides, this);
}
function createSlider(files){
var slider = $('<div class="w3-content w3-section slider" style=""></div>')
for (var i = 0; i < files.length; i++) {
prev = $('<img class="mySlide" style="">').attr("src", URL.createObjectURL(files[i]))
slider.append(prev)
}
sliders.push(slider)
// slider.data("id", inn++)
var myIndex = 0;
slider.data("slideshow", function(){
console.log(myIndex);
var slides = slider.children( ".mySlide" ).css("display", "none")
myIndex++;
if (myIndex > slides.length) {myIndex = 1}
console.log(slides[myIndex]);
$(slides[myIndex-1]).css("display", "block")
setTimeout(slider.data("slideshow"), 2000)
})
return slider
}
var sContainer = $("#slideshowContiner")
var sRows = $("#sRows")
var sCol = $("#sCol")
var btnGen = $("#btnGen")
function genGrid(){
sContainer.html("")
for (var i = 0; i < sRows.val(); i++) {
var newRow = sContainer.append('<tr></tr>')
// var newRow = sContainer.append('<div class="row flex-fill d-flex " style="border: 1px solid;"></div>')
for (var x = 0; x < sCol.val(); x++) {
var newCol = $('<td style="background-color:'+randomColor()+'"></td>')
newRow.append(newCol);
var input = $('<input webkitdirectory mozdirectory msdirectory odirectory directory multiple/>')
.attr('type', "file")
.attr('name', "file")
.on("change", function() {
cell = $(this).data("cell")
var s = createSlider(this.files)
cell.append(s)
// carousel(s)
var init = s.data("slideshow")();
})
.data("cell", newCol);;
newCol.append($(input))
}
}
}
genGrid()
btnGen.click(genGrid)
JsFiddle.
Note: on this fiddle the style="height:100vh;" are on the root div, on the original code are on the body tag.

You could set each image to a fixed height using a static unit such as px in your class, and use a few media queries to control their dimensions in different resolutions. This way you can expect what they will look like.

Related

add hyperlink with images by button or Drag and save current state [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 months ago.
Improve this question
<style>
.grid {
display: flex;
flex-wrap: wrap;
}
.grid-item {
width: 50%;
}
#media (max-width: 600px) {
.grid-item {
width: 100%;
}
}
img {
width: 100%;
}
a {
display: block;
text-align: center;
}
input[type="text"] {
width: 100%;
}
</style>
<div class="grid">
<div class="grid-item"><img src="image1.jpg" /></div>
<div class="grid-item"><img src="image2.jpg" /></div>
<div class="grid-item"><img src="image3.jpg" /></div>
<div class="grid-item"><img src="image4.jpg" /></div>
</div>
<form>
<input type="text" placeholder="Enter image URL" />
<input type="text" placeholder="Enter hyperlink URL" />
<button type="submit">Add item</button>
</form>
<script>
var grid = document.querySelector('.grid');
var gridItems = document.querySelectorAll('.grid-item');
var form = document.querySelector('form');
// Load the saved grid state from local storage
var gridState = JSON.parse(localStorage.getItem('gridState'));
if (gridState) {
for (var i = 0; i < gridState.length; i++) {
var gridItem = document.createElement('div');
gridItem.classList.add('grid-item');
gridItem.innerHTML = '<img src="' + gridState[i].imageUrl + '" />';
grid.appendChild(gridItem);
}
}
for (var i = 0; i < gridItems.length; i++) {
gridItems[i].addEventListener('click', function(event) {
window.location.href = this.querySelector('a').getAttribute('href');
});
}
form.addEventListener
('submit', function(event) {
event.preventDefault();
var imageUrl = this.querySelector('input[type="text"]').value;
var hyperlinkUrl = this.querySelector('input[type="text"]').value;
var gridItem = document.createElement('div');
gridItem.classList.add('grid-item');
gridItem.innerHTML = '<img src="' + imageUrl + '" />';
grid.appendChild(gridItem);
// Save the grid state to local storage
var gridState = [];
for (var i = 0; i < gridItems.length; i++) {
var imageUrl = gridItems[i].querySelector('img').getAttribute('src');
var hyperlinkUrl = gridItems[i].querySelector('a').getAttribute('href');
gridState.push({
imageUrl: imageUrl,
hyperlinkUrl: hyperlinkUrl
});
}
localStorage.setItem('gridState', JSON.stringify(gridState));
});
</script>
1.This is the full code I don't know why It isn't functional
2. Is there alternative way to save and change code itself? rather than use local storage?
I want functional code
Please help me, I am wandering for more than 24hours now
I suppose you want to take two inputs image's source link and the hyper link it redirects to and store these inputted values and get them when user visits site again.
1. You code was fine just that you were not getting values from those input fields. You can change.
var imageUrl = this.querySelector('input[type="text"]').value;
var hyperlinkUrl = this.querySelector('input[type="text"]').value;
to this (and add respective ids in their input tags)
var imageUrl = document.getElementById('image_url').value;
var hyperlinkUrl = document.getElementById('link').value;
<input id="image_url" type="text" placeholder="Enter image URL" />
<input id="link" type="text" placeholder="Enter hyperlink URL" />
See this my version of code here: https://jsfiddle.net/gktazfjw/
var grid = document.querySelector('.grid');
var gridItems = document.querySelectorAll('.grid-item');
var form = document.querySelector('form');
var tempLink = "https://robohash.org/"
// Load the saved grid state from local storage
var gridState = JSON.parse(localStorage.getItem('gridState'));
if (gridState) {
for (var i = 0; i < gridState.length; i++) {
var gridItem = document.createElement('div');
gridItem.classList.add('grid-item');
gridItem.innerHTML = '<a target="_blank" href="' + gridState[i].hyperlinkUrl + '"><img src="' + gridState[i].imageUrl + '" /></a>';
grid.appendChild(gridItem);
}
}
for (var i = 0; i < gridItems.length; i++) {
gridItems[i].addEventListener('click', function(event) {
window.location.href = this.querySelector('a').getAttribute('href');
});
}
form.addEventListener('submit', function(event) {
event.preventDefault();
var imageUrl = document.getElementById('image_url').value;
var hyperlinkUrl = document.getElementById('link').value;
alert(imageUrl + ": " + hyperlinkUrl)
var gridItem = document.createElement('div');
gridItem.classList.add('grid-item');
gridItem.innerHTML = '<img src="' + tempLink + imageUrl + '" />';
grid.appendChild(gridItem);
// Save the grid state to local storage
var gridState = [];
for (var i = 0; i < gridItems.length; i++) {
var imageUrl = gridItems[i].querySelector('img').getAttribute('src');
var hyperlinkUrl = gridItems[i].querySelector('a').getAttribute('href');
gridState.push({
imageUrl: imageUrl,
hyperlinkUrl: hyperlinkUrl
});
}
localStorage.setItem('gridState', JSON.stringify(gridState));
});
.grid {
display: flex;
flex-wrap: wrap;
}
.grid-item {
width: 50%;
}
#media (max-width: 600px) {
.grid-item {
width: 100%;
}
}
img {
width: 30%;
}
a {
display: block;
text-align: center;
}
input[type="text"] {
width: 100%;
}
<div class="grid">
<div target="_blank" class="grid-item">
<a href="https://example.com">
<img src="https://robohash.org/image1" />
</a>
</div>
<div target="_blank" class="grid-item">
<a href="https://example.com">
<img src="https://robohash.org/image2" />
</a>
</div>
<div target="_blank" class="grid-item">
<a href="https://example.com">
<img src="https://robohash.org/image3" />
</a>
</div>
<div target="_blank" class="grid-item">
<a href="https://example.com">
<img src="https://robohash.org/image4" />
</a>
</div>
</div>
<form>
<input id="image_url" type="text" placeholder="Enter image URL" />
<input id="link" type="text" placeholder="Enter hyperlink URL" />
<button type="submit">Add item</button>
</form>
2. Much better way is to store data in some kind of free cloud database like mongoDB, firebase, etc.
Local storage can be cleared by the user and is limited by the amount of data we can store, but is perfectly fine if it's just for practice , etc and you don't want to use your project for professional things.
But the thing is if you start using some database with your website then you will have to implement authentication logic too, to get only the desired data of any user.
var imageUrl = this.querySelector('input[type="text"]').value;
var hyperlinkUrl = this.querySelector('input[type="text"]').value
You can simply add it by using this code

Image file name stored in array then displayed through loop

I've correctly did this with displaying text in a p tag but i can't figure out why my image won't show up in the same manner and I'm not sure if it has to do with how it was set up in html.
let imgArray = ["beastiary.jpg"];
window.addEventListener("load", showImages);
function showImages() {
let i = 0;
let images = document.getElementsByTagName("img");
while (i < imgArray.length) {
images[i].innerHTML = imgArray[i]
i++
}
}
<div class="w3-col m3 l3 " style="padding-right: 5px">
<div class="w3-card-4 w3-theme-l1" id="book">
<img src="" alt="book">
<div class="w3-container w3-center w3-theme-d3">
<p></p>
</div>
</div>
</div>
I have tried to do away with using img and instead put it in a div using an id but it still won't show up. There will be more images I'm just making sure this one works first before I start adding the rest.
For showing image you need to set src to proper url
let imgArray = ["https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/800px-Image_created_with_a_mobile_phone.png"];
window.addEventListener("load", showImages);
function showImages() {
let i = 0;
let images = document.getElementsByTagName("img");
while (i < imgArray.length) {
images[i].src = imgArray[i]
i++
}
}
.img {
width: 200px;
height: 200px;
}
<img class='img'/>

Making a "Guess the Color" game and can't figure out how to add the correct answer

I'm stumped on how to make the hex code displayed at the top one of the choices on the "board." This is what I've tried so far.
var colorCode = '#' + Math.random().toString(16).slice(2, 8);
hexCode.innerHTML = colorCode;
var divs = document.getElementsByTagName('div')
for (var i = 0; i < divs.length; i++) {
divs[i].style.backgroundColor = '#' + Math.random().toString(16).slice(2, 8);
}
.panel {
height: 100px;
width: 100px;
border: 2px solid yellow;
border-radius: 25%;
}
<header>
<h1>Guess the Color</h1>
</header>
<main>
<span id="hexCode"></span>
<div id="one" class="panel"></div>
<div id="two" class="panel"></div>
<div id="three" class="panel"></div>
<div id="four" class="panel"></div>
</main>
https://jsfiddle.net/magoo/6vdfcmnL/6/
Is not clear if you want to show the text above every panel or just make one of the panel below the title the correct one; By the way i edited the code to do both.
Try to edit the code like this to check if result as intended.
HTML part:
<header>
<h1>Guess the Color</h1>
</header>
<main>
<!-- question -->
<p id="hexCodeToGuess"></p>
<br>
<!-- one -->
<span id="oneHexCode" class="label"></span>
<div id="one" class="panel"></div>
<!-- two -->
<span id="twoHexCode" class="label"></span>
<div id="two" class="panel"></div>
<!-- three -->
<span id="threeHexCode" class="label"></span>
<div id="three" class="panel"></div>
<!-- four -->
<span id="fourHexCode" class="label"></span>
<div id="four" class="panel"></div>
</main>
Javscript part:
var colorCodeToGuess = '#' + Math.random().toString(16).slice(2, 8);
// set the first label with the question (the color code to guess)
hexCodeToGuess.innerHTML = colorCodeToGuess;
// list of panels
var panels = document.getElementsByClassName('panel');
// list of labels
var labels = document.getElementsByClassName('label');
// generate the position of the right answer panel (random to make it unpredictable)
var correctPanelIndex = getRandomInt(panels.length);
// cycle trough the divs
for (var i = 0; i < panels.length; i++) {
// set by default a random new color
var currentColorCode = '#' + Math.random().toString(16).slice(2, 8);
// the div is in the right answer position => override the current color with the colorCodeToGuess generate at the start (the problem of the previous code)
if(i == correctPanelIndex){
currentColorCode = colorCodeToGuess;
}
// set the color to the panel
panels[i].style.backgroundColor = currentColorCode;
// set the text on a label above the panel
labels[i].innerHTML = currentColorCode;
}
// an useful function to get a random integer passing it the numer of values possible
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
You will notice that one of the panels have the same code of the question of the first code written below the title.
I've also commented the code so you can remove the unwanted logic consciously.
Your question is a little vague but if i got it right you want to display the background color of one of your divs in hex format. The following code will do that. I have added comments on the code to explain what im doing.
//get your panels (using selector is better that using div)
var divs = document.querySelectorAll(".panel");
for (var i = 0; i < divs.length; i++) {
divs[i].style.backgroundColor = '#' + Math.random().toString(16).slice(2, 8);
}
//get the current backgrounds of all panels and add them to an array in hex format
curruntColorsArr = [];
x = document.querySelectorAll(".panel");
for (i = 0; i < x.length; i++) {
//get background color
backgroundColors = x[i].style.backgroundColor
//convert to hex
function rgbToHex(rgb) {
return '#' + rgb.match(/[0-9|.]+/g).map((x, i) => i === 3 ? parseInt(255 * parseFloat(x)).toString(16) : parseInt(x).toString(16)).join('')
}
//push to array
curruntColorsArr.push(rgbToHex(backgroundColors));
}
//get random color from the array and set it to innerHTML
function random_item(items) {
return items[Math.floor(Math.random() * items.length)];
}
const hexCode = document.getElementById("hexCode")
hexCode.innerHTML = random_item(curruntColorsArr)
.panel {
height: 100px;
width: 100px;
border: 2px solid yellow;
border-radius: 25%;
}
<header>
<h1>Guess the Color</h1>
</header>
<main>
<span id="hexCode"></span>
<div id="one" class="panel"></div>
<div id="two" class="panel"></div>
<div id="three" class="panel"></div>
<div id="four" class="panel"></div>
</main>

Call javascript to preserve filter state when traverse from other page via href

I have a number of webpages in a report each page has a checbox filter that if selected calls javascript to show hide some elements of the page, the checkbox filter enables to true, all pages are created in advance. The user can traverse from one pages by clocking on a url .
The trouble is because the pages are created in advance the filter always default to true, even if just set to false by user on previous page. I think I need to call some javascript to set the value of the filter to the value of the filter on the calling page but because traversing form page to page via a hyperlink I dont know how to call the Javascript.
FYI
Html Filter
<div class="mb-2">
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" name="showLabels" id="showLabels" checked="checked" onclick="toggleLabelsFilter('showLabels');">
<label for="showLabels" id="showLabelslabel" class="form-check-label">
Show Labels
</label>
</div>
</div>
Example html that will have elements hidden
<figure class="figure" style="position:relative">
<a href="StatusReport00017_byfolder00021.html">
<img src="../images/E__Melco_TestMusic_WAV_WAV_Antonin Dvorak; Itzhak Perlman, Daniel Barenboim, Samuel Sanders.jpg" class="figure-img" width="200" height="200">
</a>
<div style="position:absolute; top:144px;">
<div class="badge ml-2 badge-primary">
12 files
</div>
</div>
<div style="position:absolute; top:166px;">
<div class="badge ml-2 badge-success">
12 MB
</div>
<div class="badge ml-2 badge-warning">
0 Discogs
</div>
</div>
<figcaption class="figure-caption">
<a href="StatusReport00017_byfolder00021.html">
Antonin Dvorak; Itzhak Perlman, Daniel Barenboim, Samuel Sanders
</a>
</figcaption>
</figure>
Javascript
function toggleLabelsFilter(filterName)
{
var checkbox = document.getElementById(filterName);
if(checkbox.checked)
{
var badges = document.getElementsByClassName("badge");
for (i = 0; i < badges.length; i++)
{
badges[i].style.visibility = "visible";
}
}
else
{
var badges = document.getElementsByClassName("badge");
for (i = 0; i < badges.length; i++)
{
badges[i].style.visibility = "hidden";
}
}
}
Edit Update
Attempt based on comments
Called when user selects checkbox
function toggleLabelsFilter()
{
var checkbox = document.getElementById("showLabels");
if(checkbox.checked)
{
sessionStorage.setItem("showLabels", true);
var badges = document.getElementsByClassName("badge");
for (i = 0; i < badges.length; i++)
{
badges[i].style.visibility = "visible";
}
}
else
{
sessionStorage.setItem("showLabels", false);
var badges = document.getElementsByClassName("badge");
for (i = 0; i < badges.length; i++)
{
badges[i].style.visibility = "hidden";
}
}
}
Called when page loaded
function checkFilter()
{
if(sessionStorage.getItem("showLabels")==true)
{
document.getElementById("showLabels").checked=true;
var badges = document.getElementsByClassName("badge");
for (i = 0; i < badges.length; i++)
{
badges[i].style.visibility = "visible";
}
}
else
{
document.getElementById("showLabels").checked=false;
var badges = document.getElementsByClassName("badge");
for (i = 0; i < badges.length; i++)
{
badges[i].style.visibility = "hidden";
}
}
}

How to create pair game using node values and set a setTimeout() method

I want to create a pair game that if the same textnode is matched it will set the background in white to reveal the matched textnode if not it will set a timeout and get back in original state.
The Problem of this is if I use the childNodes.nodeValue in match it saids that ChildNodes.nodeValue is not a function. And I try another code. I declare a variable that calls the element tag name of div which is I append a textNode in div. I want to compare two consecutive childNodes of div and if it is the same node, I change the color of the background to white. and I use the setTimout method, if not the color of background will go back again in original state which is black, I am pretty confused about this.
can you scan my code and help me to figure out what is the problem of this code?
here is the code.
<html>
<head>
<style>
div.row {
clear : left;
margin: auto;
width: 520px;
}
div.col {width:100px;
height:100px;
border: 3px solid black;
float : left;
margin: 10px;
font-size: 75px;
text-align: center;
background-color: black;
}
</style>
</head>
<body>
<div class="row">
<div id="00" class="col"></div>
<div id="01"class="col"></div>
<div id="02"class="col"></div>
<div id="03"class="col"></div>
</div>
<div class="row">
<div id="10" class="col"></div>
<div id="11"class="col"></div>
<div id="12"class="col"></div>
<div id="13"class="col"></div>
</div>
<div class="row">
<div id="20" class="col"></div>
<div id="21"class="col"></div>
<div id="22"class="col"></div>
<div id="23"class="col"></div>
</div>
<div class="row">
<div id="30" class="col"></div>
<div id="31"class="col"></div>
<div id="32"class="col"></div>
<div id="33"class="col"></div>
</div>
<script>
var size = 4;
var player = 0;
var board = new Array(size);
for (var i = 0; i < size; i++) {
board[i] = new Array(size);
for (var j = 0; j < size; j++) {
board[i][j] = 0;
}
}
var div_elements = document.getElementsByClassName("col");
for (var i = 0; i < div_elements.length;i++) {
div_elements[i].addEventListener("click", function() {mclick(this);});
}
var count=0;
function mclick(obj) {
if(match(div_elements.childNodes[0].nodeValue) == match(div_elements.childNodes[1].nodeValue)
{
obj.style.backgroundColor="white";
}
else{
setTimeout(function(){ obj.style.backgroundColor="white" }, 1000);
}
}
function shuffle() {
var value;
var text;
var text_node;
for (var i = 0; i < (size * size) ; i++) {
value = Math.ceil(Math.random() * 8);
board[Math.floor(i/4)][i %4] = value;
}
for (var i = 0; i < div_elements.length; i++)
{
text = board[Math.floor(i/4)][i%4];
text_node = document.createTextNode( text);
div_elements[i].appendChild(text_node);
}
}
shuffle();
</script>
</body>
</html>
You must be more specific. What kind of problem are you having? What are the error messages? What do you do that triggers the problem?
At least, put the code in a pastebin.com or something similar so that others don't need to setup a project for testing your whole stuff.

Categories