HTML onclick event doesn't work with parameter - javascript

When I click my button, which should make things visible and invisible, the whole website disappears.
What I was trying to do is to make a div with some text and probably some images and let it disappear and appear, when the button gets hit. So it would look like the Information box lists more information’s, when the user wants to read them.
But I would like to get a solution, witch I can use for more boxes like this one, so I can only copy the html and switch the onclick parameter and id from the div to 2, 3 ...
function open(x) {
var more_info = document.getElementById("project_info_" + x);
if (more_info.style.display == "none") {
more_info.style.display = "unset";
} else {
more_info.style.display = "none";
}
}
.project-box {
padding: 2vh;
margin-bottom: 3vh;
box-shadow: 0px 5px 7px rgb(136, 136, 136);
}
.project-button {
width: 20vw;
height: 3vh;
background-color: #d6d6d6;
border: none;
}
.project-button:hover {
background-color: #B50000;
color: white;
}
.project-button:focus,
.project-button:active,
.project-button:visited {
border: none;
border-radius: 0;
}
.project-closed {
display: none;
}
* {
font-family: Arial, Helvetica, sans-serif;
font-size: 2vh;
}
<div class="project-box" id="project_1">
<h3>Project 1</h3>
<p>description</p>
<div class="project-closed" id="project_info_1">
<p>Informations</p>
</div>
<button class="project-button" onclick="open(1)">More details</button>
</div>

The problem is that you have called the function open which is getting you caught up in this problem.
Because of the (horrible, horrible) way intrinsic event attributes work you are calling document.open instead of your self-defined global open function.
document.open wipes out the entire document ready for document.write to write a new one.
The quick fix is to call your function something else.
The better solution is to switch to addEventListener.

Your problem is using open - although not a reserved word - in the onclick which performs a document.open (I would have guessed window.open) and that will wipe the page in any case
Rename the function but I strongly recommend you remove the inline event handler and use an eventListener
I added the IDs of the divs to show as data attribute to the buttons you click
document.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("project-button")) {
const more_info = document.getElementById(tgt.dataset.id);
more_info.classList.toggle("project-closed");
}
})
.project-box {
padding: 2vh;
margin-bottom: 3vh;
box-shadow: 0px 5px 7px rgb(136, 136, 136);
}
.project-button {
width: 20vw;
height: 3vh;
background-color: #d6d6d6;
border: none;
}
.project-button:hover {
background-color: #B50000;
color: white;
}
.project-button:focus,
.project-button:active,
.project-button:visited {
border: none;
border-radius: 0;
}
.project-closed {
display: none;
}
* {
font-family: Arial, Helvetica, sans-serif;
font-size: 2vh;
}
<div class="project-box" id="project_1">
<h3>Project 1</h3>
<p>description</p>
<div class="project-closed" id="project_info_1">
<p>Informations</p>
</div>
<button type="button" class="project-button" data-id="project_info_1">More details</button>
</div>
<div class="project-box" id="project_2">
<h3>Project 2</h3>
<p>description</p>
<div class="project-closed" id="project_info_2">
<p>Informations</p>
</div>
<button type="button" class="project-button" data-id="project_info_2">More details</button>
</div>

Related

Pure Javascript Popup / Modal Leaving Site Consent

I tried creating simple popup leaving site consent.
demo: See demo on codepen
function exModal() {
const modalhtml=` <div class="modal-header">
🔗 You're Leaving Our Site!
<span class="close-modal">&times</span>
</div>
<div class="modal-body">
This is a link to an external site. Click OK to continue to the content. Feel free to comeback again. Make Sure To Follow Instructions Properly.
<br/><br/>
<div class="show-link"></div>
</div>
<div class="modal-footer">
<button class="close-modal">Close</button>
<button class="confirm-modal">OK</>
</div> `;
const getlink = document.querySelector('.ex-link').getAttribute('data-href');
const extra=document.createElement('div');
extra.classList.add('modal-content');
extra.innerHTML=modalhtml;
document.body.appendChild(extra);
document.querySelector('.show-link').innerHTML='('+getlink+')';
const close=document.querySelectorAll('.close-modal');
document.querySelector('.confirm-modal').addEventListener('click', (e) => {
window.open(getlink, '_blank');
});
let i;
for (i = 0; i < close.length; i++) {
close[i].addEventListener('click', (e) => {
extra.remove();
});
}
}
Problem
How can I prevent the purple button from being clicked when the modal is open.
also I want to add function like when someone click ok button, It'll close the modal while opening link in other tab.
can I handle two event in with one event listener? (reference to (2) problem) then how?
A good reference will do the job. I tried googling but mostly those tutorial includes jquery or other script
Here's what I did:
I replaced
<a class="ex-link" data-href="https://www.techlegionbd.com" onclick="exModal()">Tech Legion BD</a>
with
<button class="ex-link" type="submit">Tech Legion BD</button>
in CSS I replaced
a.ex-link {
...
}
with
button.ex-link {
Finally I used a functional approach to rewrite the scrpt thus:
CSS
button.ex-link {
width: 150px;
display: block;
margin: 10px auto;
padding: 20px;
border: 1px solid white;
background-color: #6600d6;
color: white;
font-family: 'Martel Sans', sans-serif;
font-weight: 800;
text-align: center
}
.modal-content {
position: fixed;
top: 30%;
left: 50%;
margin-left: -190px;
max-width: 380px;
border: 2px dotted #008080;
}
.modal-header {
font-size: 20px;
padding: 15px;
border-bottom: 1px solid #cecece;
background: #edfdfe;
}
.modal-body {
padding: 20px;
text-align: center;
border-bottom: 1px solid #cecece;
}
.modal-footer {
padding: 10px;
background: #edfdfe;
}
.modal-footer>button {
padding: 6px 10px;
margin-left: 5px;
cursor: pointer;
width: 50px;
background: #75e4d5;
border: 1px solid #008080;
border-radius: 4px;
}
.modal-header>.close-modal {
position: absolute;
right: 0;
top: 0;
padding: 15px;
cursor: pointer;
}
HTML
<!-- <a class="ex-link" data-href="https://www.techlegionbd.com" onclick="exModal()">Tech Legion BD</a>-->
<button class="ex-link" type="submit">Tech Legion BD</button>
JAVASCRIPT
const openModalButton = document.querySelector("button");
const extra = document.createElement('div');
const getlink = "https://www.techlegionbd.com";
const modalhtml = ` <div class="modal-header">
🔗 You're Leaving Our Site!
<!-- <span class="close-modal">&times</span>-->
</div>
<span class="close-modal" onclick="closeModal()">&times</span>
</div>
<div class="modal-body">
This is a link to an external site. Click OK to continue to the content. Feel free to comeback again. Make Sure To Follow Instructions Properly.
<br /><br />
<div class="show-link"></div>
</div>
<div class="modal-footer">
<!--<button class="close-modal">Close</button>-->
<button class="close-modal" onclick="closeModal()">Close</button>
<button class="confirm-modal">OK</>
</div> `;
function openModal() {
//refewnce variables
extra.classList.add('modal-content');
extra.innerHTML = modalhtml;
document.body.appendChild(extra);
document.querySelector('.confirm-modal').addEventListener('click', (e) => {
window.open(getlink, '_blank');
});
}
openModalButton.addEventListener("click", () => { openModal() })
function closeModal() {
document.body.removeChild(extra);
}

A Javascript script algorithm for counting the number of mouse clicks on an Html <button>. Using event Listener

I have a very simple html code that has only one button tag. I need to count the number of mouse clicks on the button using javascript.
Here is a screenshot of the Javascript code in VScode
Well, the code below can implement count on click functionality.
let clicks = 0;
document.querySelector('.btn').addEventListener('click', e => {
clicks++;
document.querySelector('.clicks').textContent = clicks
})
.btn {
border: none;
outline: none;
background-color: purple;
padding: 1rem 90px 1rem 2rem;
position: relative;
border-radius: 8px;
letter-spacing: 0.7px;
background-color: #5086bd;
color: #fff;
font-size: 21px;
font-family: "Lato", sans-serif;
cursor: pointer;
box-shadow: rgba(0, 9, 61, 0.2) 0px 4px 8px 0px;
}
<button class="btn"> Click me </button>
<div>
<p>You have clicked the button <span class="clicks"> 0</span> times</p>
</div>
Why not this?
let numberOfClicks = 0;
function addclick() {
numberOfClicks++;
document.getElementById('clicks').innerHTML = numberOfClicks;
}
document.getElementById("clickme").addEventListener("click", addclick);
<button id='clickme'>Click me!</button>
<p id='clicks'>0</p>
Update: Solution with event listener

When to Call JavaScript Toggle Function?

I have a drop down menu I need to make appear and disappear using pure JavaScript (no libraries/jQuery). Thus I am developing a toggle function. However despite trying several approaches, nothing seems to work. My current idea is to create a variable to hold the state of the menu (open or closed). Once the display of the menu changes from "none" to "block", the variable should change from "closed" to "open". Then an event listener would be added to the body element so when anything is clicked, the menu closes (i.e. the display property is changed back to "none").
Unfortunately the above doesn't seem work. When I put the If/else block outside of an event listener it fires when the page loads, but not when the menuToggle variable changes. If I put it or a function inside the menuPlaceholder event listener the menu won't open, probably due to the open and close code being called basically at the same time.
Clearly I am missing something, probably related to program control or function calling. Does anyone have any insights?
The code I am working with is below. Note the alert functions peppered throughout the code are for testing purposes only.
//Puts IDs for search preference selection box into variables
var menuPlaceholder = document.getElementById('searchSelection');
var menuDisplay = document.getElementById('searchOptions');
var boxLabel = document.getElementById('searchLabel');
//Puts IDs for text input box and submission into variables
var searchBoxPlaceholder = document.getElementById('searchInput');
var searchInput = document.getElementById('searchBox');
var submitButton = document.getElementById('submit');
//Adds class to each search option and puts ID of hidde field into variable
var searchPrefSubmission = document.getElementsByClassName('buttonSearch');
var hiddenInput = document.getElementById('searchChoice');
//Global variable to indicate whether searchOptions menu is opened or closed
var menuToggle = "closed";
//Closes element when one clicks outside of it.
function hideOnClickOutside(element) {
const outsideClickListener = event => {
if (!element.contains(event.target) && isVisible(element)) { // or use: event.target.closest(selector) === null
element.style.display = 'none'
removeClickListener()
}
}
const removeClickListener = () => {
document.removeEventListener('click', outsideClickListener)
}
document.addEventListener('click', outsideClickListener)
}
const isVisible = elem => !!elem && !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length )
//When the placeholder box is clicked, the option menu appears
menuPlaceholder.addEventListener('click', function (event){
menuDisplay.style.display = "block";
menuToggle = "open";
//Add click event to searchPref buttons
for (i = 0; i < searchPrefSubmission.length; i++) {
//Assigns value of the button to both the hidden input field and the placeholder box
searchPrefSubmission[i].addEventListener('click', function(event) {
hiddenInput.value=this.value;
boxLabel.innerHTML = this.value;
menuDisplay.style.display = "none";
menuPlaceholder.style.display = "inline-block";
});
}
});
//This code causes the text input box of the search form to appear when the background box is clicked
searchBoxPlaceholder.addEventListener('click', function(event){
searchInput.style.display = "inline";
submitButton.style.display = "inline";
//hideOnClickOutside(menuDisplay);
});
if (menuToggle == "open"){
document.body.addEventListener('click', function(event){
alert('Foo!');
})
}else{
alert('Boo!');
}
/*function toggleMenu () {
//menuDisplay.style.display = "none";
alert('Boo!');
menuToggle = "closed";
}*/
body {
font-family:Montserrat, sans-serif;
}
#searchOptionPlaceholder {
display: inline-block;
}
#searchSelection {
padding: 10px 20px;
margin-right: 10px;
background-color: #F0F3F5;
display: inline-block;
color: #000000;
width: 140px;
max-width: 200px;
max-height: 35px;
border: 2px solid black;
vertical-align: middle;
}
#searchSelection img {
float: right;
}
#searchLabel {
display: inline-block;
padding-top: 10px;
vertical-align: top;
}
#searchOptions {
display: none;
background-color: #F0F3F5;
position: absolute;
z-index: 2;
}
#searchOptions ul {
background-color: #F0F3F5;
padding: 5px;
}
#searchOptions li {
list-style-type: none;
border-bottom: 2px solid black;
}
#searchOptions li:hover {
background-color: #706868;
color: #ffffff;
}
.buttonSearch {
background-color: transparent;
border: none;
padding: 10px;
font-size: 14px;
}
.searchSubHeading {
font-size: 12px;
}
#searchInput {
display: inline-block;
background-color: #F0F3F5;
padding: 10px 100px;
position: relative;
top: 0px;
max-width: 350px;
border: 2px solid black;
vertical-align: middle;
}
#searchInput img {
position: relative;
left: 80px;
}
#searchBox {
display: none;
width: 80%;
background-color: #F0F3F5;
border: none;
font-size: 1.5em;
position: relative;
right: 50px;
vertical-align: middle;
}
#submit {
border: none;
background-image: url('https://library.domains.skidmore.edu/search/magnifyingGlass.png');
background-repeat: no-repeat;
background-size: contain;
width: 50px;
height: 30px;
position: relative;
right: -80px;
vertical-align: middle;
}
#otherLinks {
margin-top: 10px;
}
#otherLinks a{
color: #000000;
}
#otherLinks a:hover{
color: #006a52;
}
<h1>Library Search</h1>
<form method="post" action="https://library.domains.skidmore.edu/search/searchBox.php" id="librarySearch">
<div id="searchSelection"><span id="searchLabel">Catalog</span><img src="down.png" height="30px" width="30px" /></div>
<div id="searchOptions">
<ul>
<li><button type="button" name="searchPref" value="Catalog" class="buttonSearch">Catalog<br /><br /><span class="searchSubHeading">Search books and DVDs</span></button></li>
<li><button type="button" name="searchPref" value="SearchMore" class="buttonSearch">SearchMore<br /><br /><span class="searchSubHeading">Search everything</span></button></li>
<li><button type="button" name="searchPref" value="Journals" class="buttonSearch">Journals<br /><br /><span class="searchSubHeading">Search journals</span></button></li>
</ul>
</div>
<div id="searchInput">
<input type="hidden" id="searchChoice" name="searchPref" value="catalog" />
<input type="search" id="searchBox" size="60" name="searchText" placeholder="Search our holdings"/><button type="submit" id="submit"></button></div>
<div id="otherLinks">Advanced Catalog Search | WorldCat | eBooks</div>
</form>
Some issues:
Adding event listeners within an event listener is in most cases a code smell: this will add those inner listeners each time the outer event is triggered. Those listeners remain attached, and so they accumulate. So, attach all event handlers in the top-level script, i.e. on page load, and then never again.
The if ... else at the end will execute on page load, and then never again. So the value of menuToggle is guaranteed to be "closed". You need to put that if...else switch inside the handler, so that it executes every time the event triggers, at which time the menuToggle variable will possibly have a modified value.
The body element does not stretch (by default) over the whole window. If you want to detect a click anywhere on the page, you should attach the listener on the document element itself, not on document.body.
When the click on the menu placeholder is handled, you should avoid that this event "bubbles" up the DOM tree up to the document, because there you have the other handler that wants to hide the menu again. You can do this with event.stopPropagation().
The global variable is not absolutely necessary, but if you use it, then I would call it menuVisible and give it a boolean value: false at first, and possibly true later.
For actually toggling the menu, I would create a function, which takes the desired visibility (false or true) as argument, and then performs the toggle.
Do not use undeclared variables, like the for loop variable i. Define it with let.
Here is your code with those changes implemented. Of course, there is still a lot that could be improved, but I believe that goes beyond the scope of this question:
var menuPlaceholder = document.getElementById('searchSelection');
var menuDisplay = document.getElementById('searchOptions');
var boxLabel = document.getElementById('searchLabel');
var searchBoxPlaceholder = document.getElementById('searchInput');
var searchInput = document.getElementById('searchBox');
var submitButton = document.getElementById('submit');
var searchPrefSubmission = document.getElementsByClassName('buttonSearch');
var hiddenInput = document.getElementById('searchChoice');
// Changed name and type of global variable:
var menuVisible = false;
// Removed some functions ...
menuPlaceholder.addEventListener('click', function (event){
// Use new function for actually setting the visibility
toggleMenu(!menuVisible);
// Avoid that click event bubbles up to the document level
event.stopPropagation();
});
// Add these event handlers on page load, not within another handler
// Define loop variable with let
for (let i = 0; i < searchPrefSubmission.length; i++) {
//Assigns value of the button to both the hidden input field and the placeholder box
searchPrefSubmission[i].addEventListener('click', function(event) {
hiddenInput.value = this.value;
boxLabel.innerHTML = this.value;
// Use the new function for setting the visibility
toggleMenu(false);
menuPlaceholder.style.display = "inline-block";
});
}
searchBoxPlaceholder.addEventListener('click', function(event){
searchInput.style.display = "inline";
submitButton.style.display = "inline";
});
// Bind handler on document itself, and call new function
document.addEventListener('click', function(event) {
toggleMenu(false);
});
// new function to perform the toggle
function toggleMenu(show) {
menuDisplay.style.display = show ? "block" : "none";
menuVisible = show;
}
body {
font-family:Montserrat, sans-serif;
}
#searchOptionPlaceholder {
display: inline-block;
}
#searchSelection {
padding: 10px 20px;
margin-right: 10px;
background-color: #F0F3F5;
display: inline-block;
color: #000000;
width: 140px;
max-width: 200px;
max-height: 35px;
border: 2px solid black;
vertical-align: middle;
}
#searchSelection img {
float: right;
}
#searchLabel {
display: inline-block;
padding-top: 10px;
vertical-align: top;
}
#searchOptions {
display: none;
background-color: #F0F3F5;
position: absolute;
z-index: 2;
}
#searchOptions ul {
background-color: #F0F3F5;
padding: 5px;
}
#searchOptions li {
list-style-type: none;
border-bottom: 2px solid black;
}
#searchOptions li:hover {
background-color: #706868;
color: #ffffff;
}
.buttonSearch {
background-color: transparent;
border: none;
padding: 10px;
font-size: 14px;
}
.searchSubHeading {
font-size: 12px;
}
#searchInput {
display: inline-block;
background-color: #F0F3F5;
padding: 10px 100px;
position: relative;
top: 0px;
max-width: 350px;
border: 2px solid black;
vertical-align: middle;
}
#searchInput img {
position: relative;
left: 80px;
}
#searchBox {
display: none;
width: 80%;
background-color: #F0F3F5;
border: none;
font-size: 1.5em;
position: relative;
right: 50px;
vertical-align: middle;
}
#submit {
border: none;
background-image: url('https://library.domains.skidmore.edu/search/magnifyingGlass.png');
background-repeat: no-repeat;
background-size: contain;
width: 50px;
height: 30px;
position: relative;
right: -80px;
vertical-align: middle;
}
#otherLinks {
margin-top: 10px;
}
#otherLinks a{
color: #000000;
}
#otherLinks a:hover{
color: #006a52;
}
<h1>Library Search</h1>
<form method="post" action="https://library.domains.skidmore.edu/search/searchBox.php" id="librarySearch">
<div id="searchSelection">
<span id="searchLabel">Catalog</span>
<img src="down.png" height="30px" width="30px" />
</div>
<div id="searchOptions">
<ul>
<li>
<button type="button" name="searchPref" value="Catalog" class="buttonSearch">
Catalog<br /><br /><span class="searchSubHeading">Search books and DVDs</span>
</button>
</li>
<li>
<button type="button" name="searchPref" value="SearchMore" class="buttonSearch">
SearchMore<br /><br /><span class="searchSubHeading">Search everything</span>
</button>
</li>
<li>
<button type="button" name="searchPref" value="Journals" class="buttonSearch">
Journals<br /><br /><span class="searchSubHeading">Search journals</span>
</button>
</li>
</ul>
</div>
<div id="searchInput">
<input type="hidden" id="searchChoice" name="searchPref" value="catalog" />
<input type="search" id="searchBox" size="60" name="searchText" placeholder="Search our holdings"/>
<button type="submit" id="submit"></button>
</div>
<div id="otherLinks">
Advanced Catalog Search |
WorldCat |
eBooks
</div>
</form>

How to make each click (of a single button) make the content of a title change?

I wanted to do a single button which every single one of its clicks would show the same word but with different sizes, fonts, weights, etc.
Like, for example: I have the word "become", written normally with Helvetica font and a button bellow it. When I click the button, the word should change to "become" but in uppercase and bold. Then, I would click it again, and it would change to the word "become" but in lowercase and with a line through it, and so on...
In my HTML I have:
<div id="container2">
<h4 id="original">Become</h4>
</div>
<h2 id="button">Transform me!</h2>
In my CSS I have:
#font-face {
font-family: Helvetica;
src: url(Helvetica CE Regular.ttf);
}
h4{
font-family: helvetica;
margin:0 auto;
text-align:center;
width:350px;
margin-top: 7%;
}
#button{
font-family: helvetica;
font-size: 25px;
background-color: inherit;
width: 165px;
margin: 0 auto;
margin-top: 3.5%;
padding: 0.5%;
position: static;
}
#button:hover {
text-decoration: underline;
}
#original{
font-size: 90px;
font-weight: bold;
text-transform: uppercase;
}
In my Javescript I have this for now:
var botao
var original = document.getElementById('original');
botao = document.getElementById("button");
botao.onclick = function () {
original.style.cssText = 'font-style:oblique'; 'text-transform: lowercase';
}
I'm having trouble finding online an answer to solve this... I'm also not very confortable with java, for now at least...
If someone could help me out I would be very grateful.
Thank you in advance.
Here is a working version of suggestion above.
Added font size change added, works fine.
const classes = ["class1", "class2", "class3"];
var selectedIndex = 0;
document.getElementById("button").addEventListener("click", function(){
if(++selectedIndex >= classes.length) selectedIndex = 0;
document.getElementById("original").className = classes[selectedIndex];
});
.class1 {
color: red;
font-size: 1.25em;
}
.class2 {
color: blue;
font-size: 1.75em;
}
.class {
color: green;
font-size: 2.5em;
}
<div id="container2">
<h4 id="original" clasx="class1">Become</h4>
</div>
<h2 id="button">Transform me!</h2>
I would recommend using jQuery for doing this. It is friendlier to beginners.
You just need to include the jQuery CDN link in your page, and then you can use jQuery ($) functions. Using classes makes sense. See the code.
$('.transformer').click(function(){
if ($(this).siblings('h4').hasClass('original')) {
$(this).siblings('h4').addClass('uppercase-bold');
$(this).siblings('h4').removeClass('original');
}
else if($(this).siblings('h4').hasClass('uppercase-bold')){
$(this).siblings('h4').addClass('italic');
$(this).siblings('h4').removeClass('uppercase-bold');
}
else if($(this).siblings('h4').hasClass('italic')){
$(this).siblings('h4').addClass('original');
$(this).siblings('h4').removeClass('italic');
}
});
.wrapper {
border: 1px solid blue;
padding: 10px;
margin-bottom: 10px;
}
h4 {
text-transform: lowercase;
}
.uppercase-bold {
text-transform: uppercase;
font-weight: bold;
color: blue;
}
.italic {
font-style: italic;
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<h4 class="original">Become</h4>
<button class="transformer">transform me!</button>
</div>
<div class="wrapper">
<h4 class="original">To be, or not to be?</h4>
<button class="transformer">transform me!</button>
</div>

jQuery - Click registered twice

I am making a web app that utilizes several pop ups. Inside the pop up, I have customized buttons (wrapped in <label>) that upload files. When I click on the button, it fires twice. I can solve the firing twice issue with e.preventDefault(); but obviously, it doesn't open the window for the user to upload a file.
if (document.getElementById("addItemModal").style.display !== 'none'){
$("#uploadImg").on('click', function(e) {
e.preventDefault();
console.log("I clicked upload image button.");
});
$("#uploadData").on('click',function() {
console.log("I clicked upload data button.");
});
}
So it seems that the first click is what opens the window to upload files and the second click is still a mystery. Where could this second click be coming from? I've tried .unbind as well and nothing seems to work.
EDIT: Added Code - Sorry for the wait, had to take out a lot but keep it functional and true to my problem.
var modal = document.getElementById('myModal');
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
// Click Add Icon to make pop up appear
$("#myBtn").click(function() {
$("#myModal").fadeIn("fast");
$("#addModal").fadeIn("fast");
});
// Click 'x'
$("#close1").click(function() {
$("#myModal").fadeOut("fast");
});
if (document.getElementById("myModal").style.display != 'none') {
console.log("Pls don't be running twice.");
$("#upImgBtn").on('click', function(evt) {
evt.preventDefault();
console.log("I clicked upload image button.");
});
document.getElementById("upDataBtn").addEventListener('click', function() {
console.log("I clicked upload data button.");
});
}
html,
body {
height: 100%;
padding: 0;
margin: 0;
overflow: hidden;
}
/* -- Edited Headers ----------------------- */
h4 {
color: #333;
display: inline-block;
font-size: 1.6em;
letter-spacing: 3px;
font-weight: 500;
}
/* ---------------------------------------- */
.sideBar {
position: relative;
width: 18%;
height: 90%;
float: left;
z-index: 100;
border-right-style: solid;
border-right-width: thin;
border-right-color: #333;
background-color: white;
}
/* -- Header & Location ------------- */
.headbar {
height: 7%;
background-color: ghostwhite;
margin-bottom: 20px;
box-shadow: 0 3px 10px 1px #888888;
}
#myBtn {
float: right;
position: relative;
padding: 9px 3px 0 0;
cursor: pointer;
display: inline-block;
}
.uploadBtns {
padding: 10px 15px 10px 15px;
background-color: blue;
color: white;
border-radius: 5px;
cursor: pointer;
box-shadow: 0 1px 5px 0 #888;
}
#myModal {
display: none;
position: fixed;
z-index: 1000000;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.5);
}
/* Modal Content */
#addModal {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 800px;
border-radius: 15px;
color: #404040;
}
/* -- Add Location Pop Up CSS ------ */
#addTable {
width: 100%;
height: 200px;
background-color: transparent;
border-collapse: collapse;
}
td {
background-color: transparent;
border-bottom: 1px solid #333;
}
tr {
height: 100px;
}
.gridTitle {
padding-left: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sideBar" class="sideBar">
<div id="headbar" class="headbar">
<h5> Home</h5>
<div id="myBtn"><span id="addIcon">+</span>
</div>
</div>
</div>
<div id="myModal">
<div id="addModal">
<h4 id="header">ADD ITEM</h4>
<span class="myClose" id="close1">×</span>
<hr>
<table id="addTable">
<tr id="step1">
<td class="gridTitle">UPLOAD</td>
<td></td>
<td colspan="2">
<label class="btn btn-file uploadBtns" id="upImgBtn">
Upload Image
<input type="file" accept="image/*" style="display: none;" id="upImg">
</label>
<label class="btn btn-file uploadBtns" style="margin-left:120px;" id="upDataBtn">
Upload Data File
<input type="file" style="display: none;" id="upData">
</label>
</td>
</tr>
</table>
</div>
</div>
EDIT2: I haven't included the script twice in my HTML either.
All this is happening because you are adding event to the label.
Here is your code in jsfiddle.
document.getElementById("upData").addEventListener('click', function() {
alert("I clicked upload data button.");
});
You can also make a control which element fired the event. You can put your event on label and alert only if the event was from label but this doesn't stop the click event to happen on the input button.
document.getElementById("upDataBtn").addEventListener('click', function(event) {
if( event.target.tagName === "LABEL" ) {
alert("I clicked upload data button.");
}
});
It is called once or twice cause of the bubbling because the input element is part of the label and is one union and therefor also received the event if the label is click (is is not bubbling, you can't do event.stopPropagation()).
If you make
document.getElementById("upDataBtn").addEventListener('click', function(event) {
console.log(event.target.tagName);
});
This will give you two tag names
LABEL
INPUT
Try this
$(document).on('click',"#upImgBtn", function(e) {
if (e.target !== this)
return;
console.log("I clicked upload image button.");
});
$(document).on('click','#upDataBtn', function(e) {
if (e.target !== this)
return;
console.log("I clicked upload data button.");
});

Categories

Resources