get file object from called window javascript - javascript

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!

Related

Alert before executing value on select [duplicate]

I am going to make a button to take an action and save the data into a database.
Once the user clicks on the button, I want a JavaScript alert to offer “yes” and “cancel” options. If the user selects “yes”, the data will be inserted into the database, otherwise no action will be taken.
How do I display such a dialog?
You’re probably looking for confirm(), which displays a prompt and returns true or false based on what the user decided:
if (confirm('Are you sure you want to save this thing into the database?')) {
// Save it!
console.log('Thing was saved to the database.');
} else {
// Do nothing!
console.log('Thing was not saved to the database.');
}
var answer = window.confirm("Save data?");
if (answer) {
//some code
}
else {
//some code
}
Use window.confirm instead of alert. This is the easiest way to achieve that functionality.
How to do this using 'inline' JavaScript:
<form action="http://www.google.com/search">
<input type="text" name="q" />
<input type="submit" value="Go"
onclick="return confirm('Are you sure you want to search Google?')"
/>
</form>
Avoid inline JavaScript - changing the behaviour would mean editing every instance of the code, and it isn’t pretty!
A much cleaner way is to use a data attribute on the element, such as data-confirm="Your message here". My code below supports the following actions, including dynamically-generated elements:
a and button clicks
form submits
option selects
jQuery:
$(document).on('click', ':not(form)[data-confirm]', function(e){
if(!confirm($(this).data('confirm'))){
e.stopImmediatePropagation();
e.preventDefault();
}
});
$(document).on('submit', 'form[data-confirm]', function(e){
if(!confirm($(this).data('confirm'))){
e.stopImmediatePropagation();
e.preventDefault();
}
});
$(document).on('input', 'select', function(e){
var msg = $(this).children('option:selected').data('confirm');
if(msg != undefined && !confirm(msg)){
$(this)[0].selectedIndex = 0;
}
});
HTML:
<!-- hyperlink example -->
Anchor
<!-- button example -->
<button type="button" data-confirm="Are you sure you want to click the button?">Button</button>
<!-- form example -->
<form action="http://www.example.com" data-confirm="Are you sure you want to submit the form?">
<button type="submit">Submit</button>
</form>
<!-- select option example -->
<select>
<option>Select an option:</option>
<option data-confirm="Are you want to select this option?">Here</option>
</select>
JSFiddle demo
You have to create a custom confirmBox. It is not possible to change the buttons in the dialog displayed by the confirm function.
jQuery confirmBox
See this example: https://jsfiddle.net/kevalbhatt18/6uauqLn6/
<div id="confirmBox">
<div class="message"></div>
<span class="yes">Yes</span>
<span class="no">No</span>
</div>
function doConfirm(msg, yesFn, noFn)
{
var confirmBox = $("#confirmBox");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function()
{
confirmBox.hide();
});
confirmBox.find(".yes").click(yesFn);
confirmBox.find(".no").click(noFn);
confirmBox.show();
}
Call it by your code:
doConfirm("Are you sure?", function yes()
{
form.submit();
}, function no()
{
// Do nothing
});
Pure JavaScript confirmBox
Example: http://jsfiddle.net/kevalbhatt18/qwkzw3rg/127/
<div id="id_confrmdiv">confirmation
<button id="id_truebtn">Yes</button>
<button id="id_falsebtn">No</button>
</div>
<button onclick="doSomething()">submit</button>
Script
<script>
function doSomething(){
document.getElementById('id_confrmdiv').style.display="block"; //this is the replace of this line
document.getElementById('id_truebtn').onclick = function(){
// Do your delete operation
alert('true');
};
document.getElementById('id_falsebtn').onclick = function(){
alert('false');
return false;
};
}
</script>
CSS
body { font-family: sans-serif; }
#id_confrmdiv
{
display: none;
background-color: #eee;
border-radius: 5px;
border: 1px solid #aaa;
position: fixed;
width: 300px;
left: 50%;
margin-left: -150px;
padding: 6px 8px 8px;
box-sizing: border-box;
text-align: center;
}
#id_confrmdiv button {
background-color: #ccc;
display: inline-block;
border-radius: 3px;
border: 1px solid #aaa;
padding: 2px;
text-align: center;
width: 80px;
cursor: pointer;
}
#id_confrmdiv .button:hover
{
background-color: #ddd;
}
#confirmBox .message
{
text-align: left;
margin-bottom: 8px;
}
Or simply:
click me!
This plugin can help you jquery-confirm easy to use
$.confirm({
title: 'Confirm!',
content: 'Simple confirm!',
confirm: function(){
alert('Confirmed!');
},
cancel: function(){
alert('Canceled!')
}
});
This a full responsive solution using vanilla javascript :
// Call function when show dialog btn is clicked
document.getElementById("btn-show-dialog").onclick = function(){show_dialog()};
var overlayme = document.getElementById("dialog-container");
function show_dialog() {
/* A function to show the dialog window */
overlayme.style.display = "block";
}
// If confirm btn is clicked , the function confim() is executed
document.getElementById("confirm").onclick = function(){confirm()};
function confirm() {
/* code executed if confirm is clicked */
overlayme.style.display = "none";
}
// If cancel btn is clicked , the function cancel() is executed
document.getElementById("cancel").onclick = function(){cancel()};
function cancel() {
/* code executed if cancel is clicked */
overlayme.style.display = "none";
}
.popup {
width: 80%;
padding: 15px;
left: 0;
margin-left: 5%;
border: 1px solid rgb(1,82,73);
border-radius: 10px;
color: rgb(1,82,73);
background: white;
position: absolute;
top: 15%;
box-shadow: 5px 5px 5px #000;
z-index: 10001;
font-weight: 700;
text-align: center;
}
.overlay {
position: fixed;
width: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,.85);
z-index: 10000;
display :none;
}
#media (min-width: 768px) {
.popup {
width: 66.66666666%;
margin-left: 16.666666%;
}
}
#media (min-width: 992px) {
.popup {
width: 80%;
margin-left: 25%;
}
}
#media (min-width: 1200px) {
.popup {
width: 33.33333%;
margin-left: 33.33333%;
}
}
.dialog-btn {
background-color:#44B78B;
color: white;
font-weight: 700;
border: 1px solid #44B78B;
border-radius: 10px;
height: 30px;
width: 30%;
}
.dialog-btn:hover {
background-color:#015249;
cursor: pointer;
}
<div id="content_1" class="content_dialog">
<p>Lorem ipsum dolor sit amet. Aliquam erat volutpat. Maecenas non tortor nulla, non malesuada velit.</p>
<p>Aliquam erat volutpat. Maecenas non tortor nulla, non malesuada velit. Nullam felis tellus, tristique nec egestas in, luctus sed diam. Suspendisse potenti.</p>
</div>
<button id="btn-show-dialog">Ok</button>
<div class="overlay" id="dialog-container">
<div class="popup">
<p>This will be saved. Continue ?</p>
<div class="text-right">
<button class="dialog-btn btn-cancel" id="cancel">Cancel</button>
<button class="dialog-btn btn-primary" id="confirm">Ok</button>
</div>
</div>
</div>
You can intercept the onSubmit event using JavaScript.
Then call a confirmation alert and then grab the result.
Another way to do this:
$("input[name='savedata']").click(function(e){
var r = confirm("Are you sure you want to save now?");
//cancel clicked : stop button default action
if (r === false) {
return false;
}
//action continues, saves in database, no need for more code
});
xdialog provides a simple API xdialog.confirm(). Code snippet is following. More demos can be found here
document.getElementById('test').addEventListener('click', test);
function test() {
xdialog.confirm('Are you sure?', function() {
// do work here if ok/yes selected...
console.info('Done!');
}, {
style: 'width:420px;font-size:0.8rem;',
buttons: {
ok: 'yes text',
cancel: 'no text'
},
oncancel: function() {
console.warn('Cancelled!');
}
});
}
<link href="https://cdn.jsdelivr.net/gh/xxjapp/xdialog#3/xdialog.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/gh/xxjapp/xdialog#3/xdialog.min.js"></script>
<button id="test">test</button>
Made super simple, tiny vanilla js confirm dialog with Yes and No buttons.
It's a pity we can't customize the native one.
https://www.npmjs.com/package/yesno-dialog.
Another solution apart from the others is to use the new dialog element. You need to make use of show or showModal methods based on interactivity with other elements. close method can be used for closing the open dialog box.
<dialog>
<button class="yes">Yes</button>
<button class="no">No</button>
</dialog>
const dialogEl = document.querySelector("dialog");
const openDialog = document.querySelector("button.open-dialog");
const yesBtn = document.querySelector(".yes");
const noBtn = document.querySelector(".no");
const result = document.querySelector(".result");
openDialog.addEventListener("click", () => {
dialogEl.showModal();
});
yesBtn.addEventListener("click", () => {
// Below line can be replaced by your DB query
result.textContent = "This could have been your DB query";
dialogEl.close();
});
noBtn.addEventListener("click", () => {
result.textContent = "";
dialogEl.close();
});
#import url('https://fonts.googleapis.com/css2?family=Roboto:wght#300&display=swap');
body {
font-family: "Roboto";
}
button {
background: hsl(206deg 64% 51%);
color: white;
padding: 0.5em 1em;
border: 0 none;
cursor: pointer;
}
dialog {
border: 0 none;
}
.result {
margin-top: 1em;
}
<dialog>
<button class="yes">Yes</button>
<button class="no">No</button>
</dialog>
<button class="open-dialog">Click me</button>
<div class="result"></div>
Can I use?
Right now the compatibility is great with all the modern browsers.
I'm currently working on a web workflow which already has it's own notifications/dialog boxes, and I recently (like, today) created a tiny, custom (and tailored to the project needs) YES/NO dialog box.
All dialog boxes appeard over a modal layer. Full user attention is required.
I define the options configurations in this way. This options are used to define the buttons text, and the values associated to each button when there clicked:
optionsConfig = [
{ text: 'Yes', value: true },
{ text: 'No', value: false }
]
The use of the function goes something like this:
const answer = await notifier.showDialog('choose an option', options.config);
if (answer) {
// 'Yes' was clicked
} else {
// 'No' was clicked!
}
What I do, it's simply creating a async event handler for each option, it means, there is a simple handler assigned to each button. Each handler returns the value of the option. The handlers are pushed inside an array.
The array is then passed to Promise.race, and that is the return value of the showDialog method, which will correspond to the value's actual value (the one returned by the handler).
Can't provide too much code. As I said it's a very specific case, but the idea may be usefull for other implementations. Twenty lines of code or so.
A vanilla JavaScript option with a class for creating the custom modal dialog which includes a text box:
jsfiddle:
https://jsfiddle.net/craigdude/uh82mjtb/2/
html:
<!DOCTYPE html>
<html>
<style>
.modal_dialog
{
box-sizing: border-box;
background-color: #ededed;
border-radius: 5px;
border: 0.5px solid #ccc;
font-family: sans-serif;
left: 30%;
margin-left: -50px;
padding: 15px 10px 10px 5px;
position: fixed;
text-align: center;
width: 320px;
}
</style>
<script src="./CustomModalDialog.js"></script>
<script>
var gCustomModalDialog = null;
/** this could be static html from the page in an "invisible" state */
function generateDynamicCustomDialogHtml(){
var html = "";
html += '<div id="custom_modal_dialog" class="modal_dialog">';
html += 'Name: <input id="name" placeholder="Name"></input><br><br>';
html += '<button id="okay_button">OK</button>';
html += '<button id="cancel_button">Cancel</button>';
html += '</div>';
return html;
}
function onModalDialogOkayPressed(event) {
var name = document.getElementById("name");
alert("Name entered: "+name.value);
}
function onModalDialogCancelPressed(event) {
gCustomModalDialog.hide();
}
function setupCustomModalDialog() {
var html = generateDynamicCustomDialogHtml();
gCustomModalDialog = new CustomModalDialog(html, "okay_button", "cancel_button",
"modal_position", onModalDialogOkayPressed, onModalDialogCancelPressed);
}
function showCustomModalDialog() {
if (! gCustomModalDialog) {
setupCustomModalDialog();
}
gCustomModalDialog.show();
gCustomModalDialog.setFocus("name");
}
</script>
<body>
<button onclick="showCustomModalDialog(this)">Show Dialog</button><br>
Some content
<div id="modal_position">
</div>
Some additional content
</body>
</html>
CustomModalDialog.js:
/** Encapsulates a custom modal dialog in pure JS
*/
class CustomModalDialog {
/**
* Constructs the modal content
* #param htmlContent - content of the HTML dialog to show
* #param okayControlElementId - elementId of the okay button, image or control
* #param cancelControlElementId - elementId of the cancel button, image or control
* #param insertionElementId - elementId of the <div> or whatever tag to
* insert the html at within the document
* #param callbackOnOkay - method to invoke when the okay button or control is clicked.
* #param callbackOnCancel - method to invoke when the cancel button or control is clicked.
* #param callbackTag (optional) - to allow object to be passed to the callbackOnOkay
* or callbackOnCancel methods when they're invoked.
*/
constructor(htmlContent, okayControlElementId, cancelControlElementId, insertionElementId,
callbackOnOkay, callbackOnCancel, callbackTag) {
this.htmlContent = htmlContent;
this.okayControlElementId = okayControlElementId;
this.cancelControlElementId = cancelControlElementId;
this.insertionElementId = insertionElementId;
this.callbackOnOkay = callbackOnOkay;
this.callbackOnCancel = callbackOnCancel;
this.callbackTag = callbackTag;
}
/** shows the custom modal dialog */
show() {
// must insert the HTML into the page before searching for ok/cancel buttons
var insertPoint = document.getElementById(this.insertionElementId);
insertPoint.innerHTML = this.htmlContent;
var okayControl = document.getElementById(this.okayControlElementId);
var cancelControl = document.getElementById(this.cancelControlElementId);
okayControl.addEventListener('click', event => {
this.callbackOnOkay(event, insertPoint, this.callbackTag);
});
cancelControl.addEventListener('click', event => {
this.callbackOnCancel(event, insertPoint, this.callbackTag);
});
} // end: method
/** hide the custom modal dialog */
hide() {
var insertPoint = document.getElementById(this.insertionElementId);
var okayControl = document.getElementById(this.okayControlElementId);
var cancelControl = document.getElementById(this.cancelControlElementId);
insertPoint.innerHTML = "";
okayControl.removeEventListener('click',
this.callbackOnOkay,
false
);
cancelControl.removeEventListener('click',
this.callbackOnCancel,
false
);
} // end: method
/** sets the focus to given element id
*/
setFocus(elementId) {
var focusElement = document.getElementById(elementId);
focusElement.focus();
if (typeof focusElementstr === "HTMLInputElement")
focusElement.select();
}
} // end: class
The easiest way to ask before action on click is following
<a onclick="return askyesno('Delete this record?');" href="example.php?act=del&del_cs_id=<?php echo $oid; ?>">
<button class="btn btn-md btn-danger">Delete </button>
</a>
document.getElementById("button").addEventListener("click", function(e) {
var cevap = window.confirm("Satın almak istediğinizden emin misiniz?");
if (cevap) {
location.href='Http://www.evdenevenakliyat.net.tr';
}
});

How to update the actual true value="" of a input field when another field is entered

I have reviewed tonnes of articles and all solutions only update the visually displayed value as opposed to the actual value within the input tag itself.
When I click on a button a modal appears with a text input to enter a code. We will call it input1
Upon entering the code and exiting the modal the button updates to the code entered and a hidden input value gets updated as well. However the actual tags value="" remains the same.
I have tried numerous ways but all seem to only update the visual and not the true value.
Here is what I have so far but it only updates the value you see in the browser not within the tag itself.
let promoModal = document.getElementById("promoModal");
let promoBtn = document.getElementById("promo");
let promoSpan = document.getElementsByClassName("promoClose")[0];
promoBtn.onclick = function() {
promoModal.style.display = "block";
}
promoSpan.onclick = function() {
promoModal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == promoModal) {
promoModal.style.display = "none";
}
}
function updatePromo() {
let promoValue = document.getElementById("promo-value");
let producePromo = document.getElementById("promo");
let copyPromo = document.getElementById("promo-value-copy");
producePromo.innerHTML = promoValue.value;
copyPromo.innerHTML = promoValue.value;
}
/* THE MODAL */
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 5px 20px;
border: 1px solid #888;
width: 280px;
position: relative;
}
}
/* The Close Button */
.adultClose,
.promoClose {
color: #aaaaaa;
position: absolute;
right: 5px;
top: 0px;
font-size: 22px;
font-weight: bold;
cursor: pointer;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<button id="promo" type="button" class="promo">
<span class="promoCode">Promo Code +</span>
</button>
<input type="hidden" id="promo-value-copy" value="test">
<!-- Promo Modal -->
<div id="promoModal" class="modal">
<div class="modal-content">
<span class="promoClose">×</span>
<input type="text" class="promo-value" id="promo-value" value="" placeholder="Promotional code" onchange="updatePromo()">
</div>
</div>
I stripped the styling to get to the meat and potatoes.
How can I update the actual value="test" to the new value using javascript?
The innerHTML is used for changing HTML content, so for instance you can use it for changing the content of a paragraph <p id="text-to-change"></p>.
To change the input value you can use the .value property of the object.
Try to change the following line copyPromo.innerHTML = promoValue.value; with copyPromo.value = promoValue.value;
You need to change the value like this:
document.getElementById("promo-value-copy").value = promoValue.value;
so going with Barmar's suggestion I was able to update my updatePromo function to both produce the value as well as update the DOM value.
Here is the updated function. I hope it helps the community.
function updatePromo() {
let promoValue = document.getElementById("promo-value");
let producePromo = document.getElementById("promo");
let copyPromo = document.getElementById("promo-value-copy");
producePromo.innerHTML = promoValue.value;
copyPromo.innerHTML = promoValue.value;
copyPromo.setAttribute("value", promoValue.value); // suggestion given by Barmar
}
I had to leave the other element as it adds the text after the form field which is actually needed for this project however typically would not be needed.

I am trying to show two different texts in html using a modal view but the javascript overlaps and doesn't work properly

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!

How do I assign the selected indexes data to my ToolTips data?

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;
});

How Can I Make Popup Blog Content in Wordpress

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>

Categories

Resources