I'm trying to write some Javascript for a Drupal site we run. Ideally this would run on all the pages whenever the DOM class is used. This is what I have so far:
window.onload = function () {
// Get the modal
var modal = ["m1", "m2", "m3", "m4", "m5"];
for (var i = 0; i < modal.length; i++){
document.getElementById(modal[i]);
}
// Get the button that opens the modal
var btn = ["btn1", "btn2", "btn3", "btn4", "btn5", "btn6"];
for (var i = 0; i < btn.length; i++){
document.getElementById(btn[i]);
}
// When the user clicks on the button, open the modal
for (var i = 0; i < btn.length; i++)
{
btn[i].onclick = function() {
modal[i].style.display = "block";
}
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal[i].style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal[i].style.display = "none";
}
}
}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
<!-- Trigger/Open The Modal -->
<a id="myBtn">Open Me</a>
<!-- The Modal -->
<div id="modal" class="modal">
<div class="modal-content drive">
<span class="close">x</span>
<h2>Foo</h2>
<p>Random Info</p>
<p><a class="btn" href="/bar">Foo Bar</a></p>
</div>
As of now I'm getting a syntax error on this Loop
for (i = 0, i < btn.length; i++) <----This parenthesis
{
btn[i].onclick = function()
modal[i].style.display = "block";
}
Thanks for the help!
Edited: Fixed the broken JS, however, no modals will pop up. Any ideas?
This should have been a comment, but my comments are off, so I had to answer.
find this comment line:
// When the user clicks on the button, open the modal
Right below that comment, your for loop is like this:
for (var i = 0, i < btn.length; i++)
which should be :
for (var i = 0; i < btn.length; i++)
You just missed a semicolon ; after var i = 0 and added a comma , instead.
Read the error message carefully, that was a syntax error on line 77 of the mentioned file http://stacksnippets.net/js
You don't declare the variable in the scope of for loop:
for (i = 0, i < btn.length; i++)
And the next line, function is wrong, need mulstache:
btn[i].onclick = function()
The correct:
for (var i = 0; i < btn.length; i++)
{
btn[i].onclick = function(){
modal[i].style.display = "block";
}
}
Related
I am creating a gallery in PHP. Clicking on each thumbnail should open a modal window with the image and other information.
The problem is that it only works with the first thumbnail and not with the others.
this is part of the php code:
while($i !== $nIMG){
$recordIMG = $q->fetch(PDO::FETCH_ASSOC);
echo "<div class='content-img'><img src='". $recordIMG['urljpg'] ."' id='infoIMG'></div>";
$i++;
}
this is the modal window
<div class="modal" id="myModal">
<img class="modal-content" id="img01">
</div>
this is the javascript code
var modal = document.getElementById("myModal");
var img = document.getElementById("infoIMG");
var modalImg = document.getElementById("img01");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
}
I am thinking it is an ID issue which must be unique. But I don't know how to solve, could someone more experienced help me?
In that case, the php part was okay. Add onclick="openImage(this)" to it, and than move to the javascript part.
There, you would need a new function to pass the image src. I also re-named the modal image class to a more general one: image-content
// Get the modal
var modal = document.getElementById("myModal");
var modalImg = document.getElementById("image-content");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
// Look at this code: element is passed to the function
function openImage(element) {
modal.style.display = "block";
// This is where the magic happens :)
modalImg.src = element.src;
}
body {
font-family: Arial, Helvetica, sans-serif;
}
.modal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
padding-top: 100px;
/* Location of the box */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
overflow: auto;
/* Enable scroll if needed */
background-color: rgb(0, 0, 0);
/* Fallback color */
background-color: rgba(0, 0, 0, 0.4);
/* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h2>Modal Example</h2>
<!-- Trigger/Open The Modal -->
<div class='content-img'><img src="https://picsum.photos/100/100?random=1" onclick="openImage(this)"></div>
<div class='content-img'><img src="https://picsum.photos/100/100?random=2" onclick="openImage(this)"></div>
<div class='content-img'><img src="https://picsum.photos/100/100?random=3" onclick="openImage(this)"></div>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content" id="myModal">
<span class="close">×</span>
<img class="modal-content" id="image-content">
</div>
</div>
</body>
</html>
before getting your answer i tried to create two for loops in php and javascript and it works. These are the codes:
PHP:
$n = 0;
for($i = 0; $i !== $nIMG; $i++){
$n++;
$recordIMG = $q->fetch(PDO::FETCH_ASSOC);
echo "<div class='content-img'><img src='". $recordIMG['urljpg'] ."' id='infoIMG".$n."'></div>";
}
Javascript:
var nr = 0;
for(i = 0; i < 100; i++){
nr++;
var y = "infoIMG" + nr;
var img = document.getElementById(y);
var modal = document.getElementById("myModal");
var modalImg = document.getElementById("img01");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
}
}
Everything seems to work fine. Do you think it might be okay or is it better to use the code reported by you?
If I use this code, the only doubt is to understand how to pass the number of rows of the mysql database as the second parameter of the JS for loop.
So I finally created a example that is runnable and testable.
What I've done so far is I created two buttons, both of which show a tooltip when hovering over.
When you click a button it allows yuo to chose a item from a Select element.
Here is the thing..
I want to display the information about the item selected in the corresponding ToolTip.
So if I click the button headBtn and select the first option, Then I want the information about that selected option to display in the tooltip that shows when you hover over that button.
var theArray = [];
function getHeadData() {
$("#itemSelect").empty();
$.getJSON("https://api.myjson.com/bins/lf0tc", function (data) {
for (var i = 0; i < data.length; ++i) {
var html = '<option id="' + data[i].id + '">' + data[i].Name + '</option>';
$('#itemSelect').append(html);
}
theArray = data;
});
}
function getNeckData() {
$("#itemSelect").empty();
$.getJSON("https://api.myjson.com/bins/bw34w", function (data) {
for (var i = 0; i < data.length; ++i) {
var html = '<option id="' + data[i].id + '">' + data[i].Name + '</option>';
$('#itemSelect').append(html);
}
theArray = data;
});
}
$('.tooltip').mouseover(function(event){
var index = $(".tooltip").index(this);
switch (index) {
case 0:
//HeadItem
break;
case 1:
//NeckItem
break;
default:
break;
}
//How do I assign <h3> Item Name the value of theArray[i].Name?
//How do I assign Item Icon the value of theArray[i].Icon?
});
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var head = document.getElementById("headBtn");
// Get the button that opens the modal
var neck = document.getElementById("neckBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
head.onclick = function() {
modal.style.display = "block";
getHeadData();
}
// When the user clicks the button, open the modal
neck.onclick = function() {
modal.style.display = "block";
getNeckData();
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
/* Position the tooltip */
position: absolute;
z-index: 1;
}
.tooltip:hover .tooltiptext {
visibility: visible;
}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<p>Move the mouse over the text below:</p>
<!-- Trigger/Open The Modal -->
<button class="tooltip" id="headBtn">Select Helmet
<div class="tooltiptext">
<h3 class=radio> Item Name </h3>
<p class=radio> Icon </p>
</div>
</button>
<button class="tooltip" id="neckBtn">Select Necklace
<div class="tooltiptext">
<h3 class=radio> Item Name </h3>
<p class=radio> Icon </p>
</div>
</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Please Select An Item</p>
<select id="itemSelect">
</select>
</div>
</div>
I've gone another way since your solution, having only one array, can only handle one item info at a time so you have to save the data somewhere anyway.
The idea is binding a change listener to your dropdown and altering the tooltip after selection.
Be aware that, with your current setup, this won't respond to selecting the first item right away, since it's considered already selected and doesn't fire change. The simplest way get around this is by adding a placeholder option with no value and filtering it on the handler but if you don't want this placeholder element it can be done by listening to click instead.
// Find first tooltip and save contents to a variable so we can restore it
emptyTooltip = $('.tooltiptext').first().html()
function getHeadData() {
getData("https://api.myjson.com/bins/lf0tc")
// Listen for changes on the 'select'. Pass the target div where to insert the result
$('#itemSelect').change(function() {
setData('#headBtn', $(this))
});
}
function getNeckData() {
getData("https://api.myjson.com/bins/bw34w")
$('#itemSelect').change(function() {
setData('#neckBtn', $(this))
});
}
function getData(url) {
/*
Since the 'select' itself doesn't get removed from the dom,
still has the previous content and listener attached.
We remove them to avoid affecting the wrong element.
*/
$("#itemSelect").empty().off('change');
$.getJSON(url, function(data) {
// Add a placeholder 'option' so it responds to the 'change' event
$('#itemSelect').append('<option value="">Select an item</option>');
for (var i = 0; i < data.length; ++i) {
var html = '<option value="' + i + '" data-icon="' + data[i].Icon + '">' + data[i].Name + '</option>';
// Collect other item statistics in the response.
let itemStats = {};
for (key in data[i]) {
if ((key != 'Icon') && (key != 'Name')) {
itemStats[key] = data[i][key];
}
}
// Convert the option to a jQuery element and attach the data.
$html = $(html)
$html.data('stats', itemStats);
$('#itemSelect').append($html);
}
/*
This renders the placeholder option unnecessary since it forces
a selection on 'select' load. This is done to reset the tooltip
if the user dismisses the modal without selecting anything.
The placeholder option is what signals this, since it has no 'value'.
Otherwise it would force the first 'option' in the dropdown.
*/
$('#itemSelect').trigger('change')
});
}
/*
target is where to insert the results
$item is the 'select' itself. Not really necessary
since it always be '#itemSelect' and can be retrieved in the function.
*/
function setData(target, $item) {
$selection = $item.children('option:selected')
// Get target element and corresponding tooltip
$span = $(target).children('.tooltiptext')
// Check if there's an actual selection or the placeholder item
if ($selection.val() != "") {
// Insert each element in its place
$span.children('h3').text($selection.text())
// Won't allow crossorigin elements
// img = $('img').attr('src', $selection.data('icon'))
$span.children('p').text('Icon Data')
// Item stats accesible here
// $selection.data('stats')
} else {
// No selection, reset tooltip.
$span.html(emptyTooltip);
}
}
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var head = document.getElementById("headBtn");
// Get the button that opens the modal
var neck = document.getElementById("neckBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
head.onclick = function() {
modal.style.display = "block";
getHeadData();
}
// When the user clicks the button, open the modal
neck.onclick = function() {
modal.style.display = "block";
getNeckData();
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
/* Position the tooltip */
position: absolute;
z-index: 1;
}
.tooltip:hover .tooltiptext {
visibility: visible;
}
/* The Modal (background) */
.modal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
padding-top: 100px;
/* Location of the box */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
overflow: auto;
/* Enable scroll if needed */
background-color: rgb(0, 0, 0);
/* Fallback color */
background-color: rgba(0, 0, 0, 0.4);
/* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<p>Move the mouse over the text below:</p>
<!-- Trigger/Open The Modal -->
<button class="tooltip" id="headBtn">Select Helmet
<div class="tooltiptext">
<h3 class=radio> Item Name </h3>
<p class=radio> Icon </p>
</div>
</button>
<button class="tooltip" id="neckBtn">Select Necklace
<div class="tooltiptext">
<h3 class=radio> Item Name </h3>
<p class=radio> Icon </p>
</div>
</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Please Select An Item</p>
<select id="itemSelect">
</select>
</div>
</div>
Try this. I added a var for headTip and neckTip. OnChange event (that I bind on modal show) I am assigning this value. Then I am simply replacing the h3 there.
var theArray = [];
var headTip, neckTip;
function getHeadData() {
$("#itemSelect").empty();
$.getJSON("https://api.myjson.com/bins/lf0tc", function (data) {
for (var i = 0; i < data.length; ++i) {
var html = '<option id="' + data[i].id + '">' + data[i].Name + '</option>';
$('#itemSelect').append(html);
}
theArray = data;
});
}
function getNeckData() {
$("#itemSelect").empty();
$.getJSON("https://api.myjson.com/bins/bw34w", function (data) {
for (var i = 0; i < data.length; ++i) {
var html = '<option id="' + data[i].id + '">' + data[i].Name + '</option>';
$('#itemSelect').append(html);
}
theArray = data;
});
}
$('.tooltip').mouseover(function(event){
var index = $(".tooltip").index(this);
switch (index) {
case 0:
//HeadItem
$(".tooltip h3").html(headTip);
break;
case 1:
//NeckItem
$(".tooltip h3").html(neckTip);
break;
default:
break;
}
//How do I assign <h3> Item Name the value of theArray[i].Name?
//How do I assign Item Icon the value of theArray[i].Icon?
});
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var head = document.getElementById("headBtn");
// Get the button that opens the modal
var neck = document.getElementById("neckBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
head.onclick = function() {
modal.style.display = "block";
getHeadData();
$("#itemSelect").off("change").on("change", function(e){
headTip = $(e.currentTarget).val()
});
}
// When the user clicks the button, open the modal
neck.onclick = function() {
modal.style.display = "block";
getNeckData();
$("#itemSelect").off("change").on("change", function(e){
neckTip = $(e.currentTarget).val()
});
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
/* Position the tooltip */
position: absolute;
z-index: 1;
}
.tooltip:hover .tooltiptext {
visibility: visible;
}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<p>Move the mouse over the text below:</p>
<!-- Trigger/Open The Modal -->
<button class="tooltip" id="headBtn">Select Helmet
<div class="tooltiptext">
<h3 class=radio> Item Name </h3>
<p class=radio> Icon </p>
</div>
</button>
<button class="tooltip" id="neckBtn">Select Necklace
<div class="tooltiptext">
<h3 class=radio> Item Name </h3>
<p class=radio> Icon </p>
</div>
</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Please Select An Item</p>
<select id="itemSelect">
</select>
</div>
</div>
You'd just do it like this:
$('.tooltip').mouseover(function(event){
var index = $(".tooltip").index(this);
switch (index) {
case 0:
//HeadItem
break;
case 1:
//NeckItem
break;
default:
break;
}
//NEW LINES
$("#headBtn > .tooltiptext > h3.radio").html(theArray[index].Name;
$("#headBtn > .tooltiptext > p.radio").html(theArray[index].Icon;
});
I want to display my reference works on index. I limited the words. My aim is this: User who wants to learn detail information about post, will click the post thumbnail and the rest of content will open with popup.
I used w3css modal to make it. My javascript codes are:
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
But only the first post seems like that. The others have no reaction.
Thanks.
I want to make all thumbnails like that
I made some revision about that. I used fancybox 2 and change my code with this
<?php the_post_thumbnail('thumbnail', array('class' => 'aligncenter')); ?>
<div id="inline1" style="width:400px;display: none;">
<?php the_post_thumbnail('thumbnail', array('class' => 'aligncenter')); ?><?php the_content(); ?>
</div>
Now all the thumbnails open with fancybox but this time the other thumbnails' contents are same with the first post.
I don't think create a modal element in every container is a right way to go.
Instead, I will suggest you make only one modal element, and change the content of
that modal when any image got clicked.
thus, here is a demo that I just made
JSbin
The step will be
find out all container elems
bind those elems with click event
when user click one elem, extract the text and image src of that elem
inject into modal-body
removve hide class
It's fine to have modals mixed in. You have to be a little picky about event handlers and which one to close, but it's not too bad.
var sites = document.querySelectorAll('.site');
var closes = document.querySelectorAll('.close');
var ix;
for (ix = 0; ix < sites.length; ix++) {
sites.item(ix).addEventListener('click', showModal);
}
for (ix = 0; ix < closes.length; ix++) {
closes.item(ix).addEventListener('click', closeModal);
}
function showModal(e) {
e.stopPropagation();
this.querySelector('.modal').style.display = "block";
}
function closeModal(e) {
e.stopPropagation();
try {
getParent(this, 'modal').style.display = "none";
} catch (e) {
console.warn('Failed to find my daddy.');
}
}
function getParent(el, cls) {
while (el.parentElement) {
el = el.parentElement;
if (el.classList.contains(cls)) return el;
}
return null;
}
.site {
display: inline-block;
}
.thumbnail {
width: 100px;
height: 100px;
border: 1px solid black;
margin: 10px;
}
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.4);
}
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 50%;
}
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
line-height: 28px;
font-weight: bold;
cursor: pointer;
}
.close:hover,
.close:focus {
color: #000;
}
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<div class="container">
<div class="site">
<div class="thumbnail"></div>
<div class="modal">
<div class="modal-content">
<span class="close">×</span> First Item
</div>
</div>
</div>
<div class="site">
<div class="thumbnail"></div>
<div class="modal">
<div class="modal-content">
<span class="close">×</span> Second Item
</div>
</div>
</div>
</div>
In the code below, when I click on one of the two images it opens a gallery, and if I click on the other one it should open a different gallery. It works, but not as I expected because as you can see on the snippet there are some empty slides in each gallery. Can you help me solve this problem? Thank you!
// Get the image and insert it inside the modal
function imgg(id){
var modal = document.getElementById(id);
var modalImg = document.getElementById('mySlides');
modal.style.display = "block";
modalImg.src = this.src;
}
// When the user clicks on <span> (x), close the modal
function clos(id) {
var modal = document.getElementById(id);
modal.style.display = "none";
}
// Sliseshow
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
showDivs(slideIndex += n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("mySlides");
if (n > x.length) {slideIndex = 1}
if (n < 1) {slideIndex = x.length} ;
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block";
}
#myImg {
border-radius: 5px;
cursor: pointer;
transition: 0.3s;
}
#myImg:hover {opacity: 0.7;}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}
/* Modal Content (image) */
.mySlides {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
box-shadow: 0px 0px 50px -6px #000;
}
#-webkit-keyframes zoom {
from {-webkit-transform:scale(0)}
to {-webkit-transform:scale(1)}
}
#keyframes zoom {
from {transform:scale(0)}
to {transform:scale(1)}
}
/* The Close Button */
.close {
position: absolute;
top: 15px;
right: 100px;
color: #f1f1f1;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
}
.close:hover,
.close:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}
/* 100% Image Width on Smaller Screens */
#media only screen and (max-width: 700px){
.mySlides {
width: 100%;
}
}
.w3-btn-floating {
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="test.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
</head>
<body>
<img id="myImg" onClick="imgg('myModal')" src="http://www.gettyimages.pt/gi-resources/images/Homepage/Hero/PT/PT_hero_42_153645159.jpg" alt="" width="300" height="200">
<img id="myImg" onClick="imgg('myModal1')"src="http://cue.me/kohana/media/frontend/js/full-page-scroll/examples/imgs/bg2.jpg" alt="" width="300" height="200">
<!-- The Modal -->
<div id="myModal" class="modal">
<span onclick="clos('myModal')" class="close">×</span>
<img class="mySlides" id="img_modal" src="http://cue.me/kohana/media/frontend/js/full-page-scroll/examples/imgs/bg2.jpg" >
<img class="mySlides" id="img_modal" src="http://cdn.theatlantic.com/assets/media/img/photo/2015/11/images-from-the-2016-sony-world-pho/s01_130921474920553591/main_900.jpg" >
<a class="w3-btn-floating" style="position:absolute;top:45%;left:280px;" onclick="plusDivs(-1)">❮</a>
<a class="w3-btn-floating" style="position:absolute;top:45%;right:280px;" onclick="plusDivs(1)">❯</a>
</div>
<div id="myModal1" class="modal">
<span onclick="clos('myModal1')" class="close">×</span>
<img class="mySlides" id="img_modal" src="http://www.gettyimages.pt/gi-resources/images/Homepage/Hero/PT/PT_hero_42_153645159.jpg" >
<img class="mySlides" id="img_modal" src="http://i.dailymail.co.uk/i/pix/2016/03/22/13/32738A6E00000578-3504412-image-a-6_1458654517341.jpg" >
<a class="w3-btn-floating" style="position:absolute;top:45%;left:280px;" onclick="plusDivs(-1)">❮</a>
<a class="w3-btn-floating" style="position:absolute;top:45%;right:280px;" onclick="plusDivs(1)">❯</a>
</div>
</body>
</html>
I'm not 100% sure, but this line
var x = document.getElementsByClassName("mySlides");
should return 4 items. That would explain why you are getting 2 empty slides in your slider. Try filtering first by id (e.g. "myModal" or "myModal1") and afterwards get the number of the contained "mySlides"-classes.
so you can do it like this:
var activeModalId = "";
// Get the image and insert it inside the modal
function imgg(id){
activeModalId = id;
var modal = document.getElementById(activeModalId);
var modalImg = modal.getElementsByClassName('mySlides');
modal.style.display = "block";
showDivs(0);
}
// When the user clicks on <span> (x), close the modal
function clos() {
var modal = document.getElementById(activeModalId);
modal.style.display = "none";
activeModalId = "";
}
// Sliseshow
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
showDivs(slideIndex += n);
}
function showDivs(n) {
var i;
var x = document.getElementById(activeModalId).getElementsByClassName("mySlides");
if (n > x.length) {slideIndex = 1;}
if (n < 1) {slideIndex = x.length;}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block";
}
On top, you declare your active modal. It will be set, reused, and removed by your functions.
From what I can see there are some url typos.
For example: you have ihttp where it should be http.
In the mouse one there's an unnecessary url termination after .jpg: ?1448476701
you need to pass "this" into function like
onClick="imgg('myModal',this)"
now in function get it
function imgg(id,this){
var modal = document.getElementById(id);
var modalImg = document.getElementById('mySlides');
modal.style.display = "block";
modalImg.src = this.src;}
What I'm trying to accomplish is a java readmore/readless content toggle function that disable other content when one content's onclick triggers. I'm using getElementsByClassName, setTimeout, and transition.
The problem I'm having is that display: none is not responding to setTimeout. Any suggestion outside of javascript is welcome too.
Here is the Javascript:
function toggle(cont, tog, id) {
for (var i = 0; i < cont.length; i++) {
if (tog[id].innerHTML != "Click Here to Read Less!") {
/* Toggle On */
tog[id].innerHTML = "Click Here to Read Less!";
cont[id].style.height = "250px";
/* Disable other */
setTimeout(function () { cont[i].style.display = "none" }, 500);
setTimeout(function () { tog[i].style.display = "none" }, 500);
for (var x = 0; x < cont.length; x++) {
cont[x].style.opacity = "0";
tog[x].style.opacity = "0";
setTimeout(function () { cont[x].style.display = "none" }, 500);
setTimeout(function () { tog[x].style.display = "none" }, 500);
if (cont[id] == cont[x]) {
cont[id].style.opacity = "1";
tog[id].style.opacity = "1";
}
}
} else {
/* Toggle Off */
tog[id].innerHTML = "Click Here to Read More!";
cont[id].style.height = "100px";
/* Enable other */
for (var x = 0; x < cont.length; x++) {
cont[x].style.opacity = "1";
tog[x].style.opacity = "1";
cont[x].style.display = "block";
tog[x].style.display = "block";
}
}
}
}
Here is my HTML:
<div class="content">
<p>
Content Here!
</p>
</div>
Click Here to Read More!
<div class="content">
<p>
Content Here!
</p>
</div>
Click Here to Read More!
<div class="content">
<p>
Content Here!
</p>
</div>
Click Here to Read More!
And CSS for formatting sake:
/* Centering Content */
#wrapper {
margin: 0 auto;
height: auto;
width: 70%;
text-align: center;
font-family: Sans-Serif, Calibri;
}
/* Styling Content */
.content {
padding: 25px 50px;
margin: 0 auto;
height: 100px;
width: 500px;
display: block;
text-align: left;
overflow: hidden;
-webkit-transition: all 0.5s;
transition: all 0.5s;
}