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;
});
Related
Basically, I have a register page I'm trying to finish and at the checkbox where you agree with terms I have this text
I agree to NAME's "Terms & Conditions" and their "Privacy Policy".
Between the double-quotes there are two separate paragraphs with on click calls to a JavaScript function to two different ".js" files. First one represents the calls and operations made for the first button "Terms & Conditions" and so on. When I try to mix them, they either show the same text, or they don't show anything at all. I will also leave a small bit of code because I believe it's easier to understand my problem.
I've tried mixing them together in a single js files but it worked even worse afterwards. When I take one of the files out, the other works properly.
<label class="auth_margin"><input id="agree" type="checkbox" name="agree"> I agree to NAME's </label><p id="termsBtn"> Terms & Conditions</p> and their <p id="privacyBtn">Privacy Policy.</p><br/>
And the JavaScript files:
var modal = document.getElementById('termsModal');
var btn = document.getElementById("termsBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == pmodal) {
pmodal.style.display = "none";
}
}
var pmodal = document.getElementById('privacyModal');
var pbtn = document.getElementById("privacyBtn");
var span = document.getElementsByClassName("close")[0];
pbtn.onclick = function() {
pmodal.style.display = "block";
}
span.onclick = function() {
pmodal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == pmodal) {
pmodal.style.display = "none";
}
}
Does the following code behaves as you expected? You need a single js file for it. There are some style edits, but you can change them afterwards from CSS. Also, I preferred to use <span> instead of <p> for the two click-able texts. The difference is that <p> is a block element and <span> is not. They look nicer on a single line (in my opinion).
Nothing fancy, plain html/css/js.
var tbtn = document.getElementById("termsBtn");
var pbtn = document.getElementById("privacyBtn");
var tmodal = document.getElementById('tmodal');
var pmodal = document.getElementById('pmodal');
tbtn.onclick = function() {
pmodal.style.display = "none";
tmodal.style.display = "block";
};
pbtn.onclick = function() {
tmodal.style.display = "none";
pmodal.style.display = "block";
};
window.onclick = function(event) {
if (event.target == pmodal) {
pmodal.style.display = "none";
} else if (event.target == tmodal) {
tmodal.style.display = "none";
}
}
#termsBtn,
#privacyBtn {
color: blue;
}
/* 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;
}
<label class="auth_margin"><input id="agree" type="checkbox" name="agree"> I agree to NAME's </label><span id="termsBtn"> Terms & Conditions</span> and their <span id="privacyBtn">Privacy Policy.</span><br/>
<div id="tmodal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Some text for Terms & Conditions</p>
</div>
</div>
<div id="pmodal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Some text for Privacy Policy</p>
</div>
</div>
Cheers!
I am trying to open a window and process the file in the calling JavaScript. I can pass the file name using localStorage but if I return the file I can't get it right.
I can't use this solution due to restrictions of the system I am calling the JavaScript from:
var fileSelector = document.createElement('input');
fileSelector.setAttribute('type', 'file');
fileSelector.click();
Can a file object be passed using localStorage or should I use another method?
My code is:
<!DOCTYPE html>
<html>
<script language="JavaScript">
function testInjectScript2(){
try {
var myhtmltext =
'<input type="file" id="uploadInput3" name=\"files[]" onchange=\'localStorage.setItem("myfile",document.getElementById("uploadInput3").files[0]);\' multiple />';
console.log("myhtmltext="+myhtmltext);
var newWin2 = window.open('',"_blank", "location=200,status=1,scrollbars=1, width=500,height=200");
newWin2.document.body.innerHTML = myhtmltext;
newWin2.addEventListener("unload", function (e) {
if(localStorage.getItem("myfile")) {
var f = localStorage.getItem("myfile");
alert ('in function.f='+f);
alert ('in function.f.name='+(f).name);
localStorage.removeItem("myfile");
}
});
} catch (err) {
alert(err);
}
}
</script>
<body>
<input type="button" text="testInjectScript2" onclick="testInjectScript2()" value="testInjectScript2" />
</body>
</html>
First of all, welcome to SO. If I get you right, you want to upload a file using a new window and get that file using localStorage onto your main page. This is a possible solution. However, please do also note that the maximum size of the localStorage can vary depending on the user-agent (more information here). Therefore it is not recommend to use this method. If you really want to do this, please have a look at the first snippet.
var read = document.getElementById("read-value"), open_win = document.getElementById("open-win"), win, p = document.getElementById("file-set");
open_win.addEventListener("click", function(){
win = window.open("", "", "width=200,height=100");
win.document.write(
'<input id="file-input" type="file"/>' +
'<script>' +
'var input = document.getElementById("file-input");' +
'input.addEventListener("change", function(){window.localStorage.setItem("file", input.files[0]);})'+
'<\/script>'
);
})
read.addEventListener("click", function(){
var file = window.localStorage.getItem("file");
if(file){
p.innerText = "file is set";
}else{
p.innerText = "file is not set";
}
})
<button id="open-win">Open window</button>
<br><br>
<!-- Check if file is set in localStorage -->
<button id="read-value">Check</button>
<p id="file-set" style="margin: 10px 0; font-family: monospace"></p>
<i style="display: block; margin-top: 20px">Note: This only works locally as SO snippets lack the 'allow same origin' flag. i.e. just copy the html and js into a local file to use it.</i>
However, why not use a more elegant solution:
Simply using a modal. When the input value changes you can simply close the modal and get the file value without all the hassle of a localStorage.
// Get the modal, open button and close button
var modal = document.getElementById('modal'),
btn = document.getElementById("open-modal"),
span = document.getElementById("close"),
input = document.getElementById("file-input"),
label = document.getElementById("input-label"), file;
// When the user clicks the button, open the modal
btn.addEventListener("click", function() {
modal.style.display = "block";
})
// When the user clicks on <span> (x), close the modal
span.addEventListener("click", function() {
modal.style.display = "none";
})
input.addEventListener("change", function(){
file = input.files[0];
modal.style.display = "none";
//Change value of the label for nice styling ;)
label.innerHTML = input.files[0].name;
//do something with your value
})
// When the user clicks anywhere outside of the modal, close it
window.addEventListener("click", function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
})
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 10px; /* 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 h2 {
font-family: sans-serif;
font-weight: normal;
}
/* 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;
}
/* Input styles, added bonus */
.file-input {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
.file-input + label {
font-size: 1.25em;
font-weight: 700;
padding: 10px 20px;
border: 1px solid #888;
display: inline-block;
cursor: pointer;
font-family: sans-serif;
}
.file-input:focus + label,
.file-input + label:hover {
background-color: #f7f7f7;
}
<!-- Trigger/Open The Modal -->
<button id="open-modal">Open Modal</button>
<!-- The Modal -->
<div id="modal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span id="close" class="close">×</span>
<h2><i>Upload a file?</i></h3>
<input id="file-input" name="file-input" class="file-input" type="file"/>
<label id="input-label" for="file-input">Upload a file</label>
</div>
</div>
Hope it helps! Let me know!
Cheers!
I tried to create a function to show and hide a div, to hide the div user can use close button or click outside the div, but the problem is the close function to hide the div if user click element outside the div run first before i the div is showed:
html:
$('#close-add').on('click', function() {
$("#add-shipping-modal").hide();
});
$('#new-shipping').on('click', function() {
$("#add-shipping-modal").show();
});
$('body').click(function(event) {
setTimeout(
if (!$(event.target).closest('#add-shipping-modal').length && !$(event.target).is('#add-shipping-modal')) {
if ($("#add-shipping-modal").css('display') != 'none') {
$("#add-shipping-modal").hide();
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="new-shipping'">Open Div</button>
<div id="add-shipping-modal" style="display:none">
<button id="close-add">Close Div</button>
<p> Show Me </p>
</div>
when i click the #new-shipping button, the hidden div won't show up, i guess it's because when i click the #new-shipping button, it shows the div first and then trigger the body click function
There is already a solution provided at W3Schools.
Check Here: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal
Snippet
// 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 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";
}
}
/* 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;
}
<h2>Modal Example</h2>
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
You have added ' extra in your code after new-shipping
<button id="new-shipping'">Open Div</button>
should be
<button id="new-shipping">Open Div</button>
https://jsfiddle.net/bntnfhLm/
Also please change the body click function by using preventdefault/stopPropagation
$("#add-shipping-modal").click(function(e){
e.stopPropagation();
});
$(document).click(function(){
$("#add-shipping-modal").hide();
});
try this
$('#new-shipping').on('click', function () {
$("#add-shipping-modal").show();
return false;
});
$(document).click(function (event) {
$("#add-shipping-modal").hide();
});
try this
$('#close-add').on('click', function () {
$("#add-shipping-modal").hide();
});
$('#new-shipping').on('click', function () {
$("#add-shipping-modal").show();
return false;
});
$("#add-shipping-modal").click(function () { return false; });
$(document).click(function (event) {
$("#add-shipping-modal").hide();
});
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";
}
}
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>