Changing CSS Display property with Javascript but keeps disappearing - javascript

I have a div element in my page which I want to make visible only upon the click of a button. This works as expected, except the div promptly disappears again and I cannot get it to remain visible.
function btnAddItem_Click() {
document.getElementById("add-item-popup").style.display = "block"
}
.add-item-popup {
width: 400px;
height: 550px;
display: none;
background-color: #ededed;
position: fixed;
right: 40%;
top: 20%;
}
<div class="add-item-popup" id="add-item-popup">
//Contains a form
</div>
<button onclick="btnAddItem_Click()">Add Item</button>

I'm going to make a reasonable assumption but an assumption nonetheless with this solution. The assumption is your <button> tag with your onclick handler is inside of another form. If so, replace this line here:
<button onclick="btnAddItem_Click()">Add Item</button>
To become this code:
<button type="button" onclick="btnAddItem_Click()">Add Item</button>
Explanation: When button is inside a form without type="button" specified, it will submit the form, and in your case, reload the page where the css then of course is anew. Thus you only see a "blip" of the displayed div.

Use This Code your issue is resolved.
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>

I also agree with #GetSet, I created this little jsfiddle in order to reproduce the issue inside a form. In case we don't form, there's no issue.
You can reproduce the issue by removing/adding the button attribute type like recomended by #GetSet.
[Here it is an example][1]

Related

Why can't I use javascript to change the visibility property to hidden

I'm using javascript, so that when a user presses a button, a div will appear/disappear by changing the visibility property of the div. It works when the div is hidden and I want it to appear. However, when I presses the button again, it does not become hidden as it should.
document.getElementById("SmileyButton").addEventListener("click", getSmileys);
function getSmileys() {
var button = document.getElementById("SmileyDiv").style.visibility = 'visible';
// document.getElementById("SmileyDiv").style.visibility = 'visible';
if (button.visibility == 'hidden') {
button.visibility = 'visible'
} else {
button.visibility = 'hidden'
}
}
.enterPostBackground {
background-color: gainsboro;
width: 400px;
height: 50px;
}
#SmileyDiv {
height: 80px;
width: 160px;
background-color: grey;
overflow: scroll;
visibility: hidden;
}
<br>
<br>
<div id="SmileyDiv"></div>
<div class="enterPostBackground">
<button class="test" id="SmileyButton" style="font-size: 30px;float:left; " type="button" onclick="getSmileys()">&#128515</button>
</div>
This may solve your problem.
Changes I did,
I removed the onclick from the button. You don't need it as long as you have registered the click event in the JavaScript side.
I fixed your HTML as you had incorrect markup. _(You forgot to close the <script> tag, as well you forgot to close the second div tag.
I change the logic of your script to make it more performant.
<!DOCTYPE html>
<html>
<head>
<style>
.enterPostBackground {
background-color: gainsboro;
width: 400px;
height: 50px;
}
#SmileyDiv {
height: 80px;
width: 160px;
background-color: grey;
overflow: scroll;
visibility: hidden;
}
</style>
</head>
<body>
<br>
<br>
<div id="SmileyDiv"></div>
<div class="enterPostBackground">
<button
class="test"
id="SmileyButton"
style="font-size: 30px;float:left;"
type="button"
>&#128515</button>
</div>
</body>
</html>
<script>
// I get the SmileyDiv here. This is because it runs only once, and makes
// your script more performant.
var button = document.getElementById("SmileyDiv");
document.getElementById("SmileyButton").addEventListener("click", getSmileys);
// I set the initial visibility status here
button.style.visibility = 'visible';
function getSmileys() {
// You had forgot to add the `.style` in the button property. That's
// why the button didn't worked properly.
if (button.style.visibility === 'hidden') {
button.style.visibility = 'visible'
} else {
button.style.visibility = 'hidden'
}
}
</script>
There are a couple of problems there.
You're assigning the result of document.getElementById("SmileyDiv").style.visibility = 'visible'; to button. The result of an assignment expression is the value that was assigned, so button will be "visible".
Then you're trying to use a visibility property on button, but strings don't have that property. You probably meant to assign the result of document.getElementById("SmileyDiv") to button, but even then, you'd need button.style.visibility, not just button.visibility.
The style property only reflects the element's directly-assigned style information, not anything applied to it by CSS. Your div doesn't have visibility: xxx in its style attribute, it inherits it via CSS. You need to use getComputedStyle to get the computed style of the div.
You're using addEventListener and an onclick, so your function is getting called twice. Just use addEventListener.
button is an odd variable name for a div. :-)
See comments:
document.getElementById("SmileyButton").addEventListener("click", getSmileys);
function getSmileys() {
// It's a div, not a button
var div = document.getElementById("SmileyDiv");
// ** Get the *computed* style of the div
var style = getComputedStyle(div);
if (style.visibility !== 'hidden') {
div.style.visibility = 'hidden'
} else {
div.style.visibility = 'visible'
}
}
.enterPostBackground {
background-color: gainsboro;
width: 400px;
height: 50px;
}
#SmileyDiv {
height: 80px;
width: 160px;
background-color: grey;
overflow: scroll;
visibility: hidden;
}
<br>
<br>
<div id="SmileyDiv"></div>
<div class="enterPostBackground">
<button class="test" id="SmileyButton" style="font-size: 30px;float:left; " type="button">&#128515</button>
</div>
You are checking for button.visibility. Your button does not have a visibility attribute. You should check for button.style.visibility. You are also assigning the click listener twice, once in JS and the other in your HTML. This would cause the hide/show process to be reversed everytime.
var button = document.getElementById("SmileyButton");
button.addEventListener("click", getSmileys);
function getSmileys() {
var smileyDiv = document.getElementById("SmileyDiv");
if(smileyDiv.style.visibility == 'hidden') {
smileyDiv.style.visibility = 'visible'
} else {
smileyDiv.style.visibility = 'hidden'
}
}
.enterPostBackground {
background-color: gainsboro;
width: 400px;
height: 50px;
}
#SmileyDiv {
height: 80px;
width: 160px;
background-color: grey;
overflow: scroll;
}
<br>
<br>
<div id="SmileyDiv"></div>
<div class="enterPostBackground">
<button class="test" id="SmileyButton" style="font-size: 30px;float:left;visibility:hidden" type="button">&#128515</button>
</div>

Input field is not focusing when clicked

I have an <input> field inside a div that is giving me trouble.
It is inside a div with position absolute. When I click on it, it does not get the focus, so I cannot type inside it.
The other parts of an input field work as they should: The cursor changes to the text symbol when over it, I can focus on it using the right-click with the mouse or the Tab key and when it DOES get focus I can type on it normally.
I even binded a console log to it when clicked, just to make sure the the correct element being clicked. The log does happen, but it still doesn't get the focus on clicking.
Does anyone have an idea of what may be happening here?
Edit: added more parts of my code, sorry for having such little code before.
Here is my code:
// link that makes the form appear, on another part of the UI
jQuery("#link").on("click", function() {
jQuery(".form").show()
})
jQuery("#close-button").on("click", function() {
jQuery(".form").hide()
})
// This was added to test if the click was happening,
// it does not work with or without this
jQuery("#input-field").on("click", function(e) {
console.log("clicked")
console.log(e.target) // this is returning the "input-field" element
})
.form {
background-color: #EAE8E8;
position: absolute;
width: 99%;
right: 0;
z-index: 100;
bottom: 0;
display: none;
border: 1px solid;
}
#close-button {
float: right;
cursor: pointer;
}
/* input-field doesn't have any CSS defined by code yet */
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="link">Click to show form</button>
<div class="form">
<!-- this has position: absolute -->
<img src="'/close.png" id="close-button">
<!-- Here are some other images that can be clicked... that all works fine -->
<input id="input-field" />
<!-- this is not getting focused when clicked -->
</div>
You might add .focus() to autofocus your desired input. Here is your example:
jQuery("#link").on("click", function() {
jQuery(".form").show()
// Add to auto focus your input
jQuery("#input-field").focus();
})
jQuery("#close-button").on("click", function() {
jQuery(".form").hide()
})
.form {
background-color: #EAE8E8;
position: absolute;
width: 99%;
right: 0;
z-index: 100;
bottom: 0;
display: none;
border: 1px solid;
}
#close-button {
float: right;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="link">Click to show form</button>
<div class="form">
<img src="'/close.png" id="close-button">
<input id="input-field" />
</div>

TypeScript Modal Window

I need to show a Modal in TypeScript. I don't want to use any library(bootstrap,..) to style it, I have to use own less styling for it. what I can use to Create a Modal? it can be a javascript modal that supported by typescript and by all browsers.
I tried to use showModal() like this:
This is my TypeScript Code:
function CreateModal() {
document.getElementById("myDialog").showModal();
}
It gave me this error - showModal is not exists.
even if It works it is not supported in IE and Firefix only works in chrome.
and this is my index.html
<script src="scripts/TypeScripts/Modal.js"></script>
<button onclick="CreateModal()">Show dialog</button>
<dialog id="myDialog">This is a dialog window</dialog>
I tried to use Onclick as well but it says does not existed.
span.onclick = function () {
modal.style.display = "none";
}
I know it's been a few months since this question was asked, but I recently had the same problem and was able to get a solution working.
In the typescript, you can ignore the need for the HTMLDialogElement by casting your dialog to type any.
openMyDialog() {
let myDialog:any = <any>document.getElementById("myDialog");
myDialog.showModal();
}
In your HTML, you just attached this function to the angular (click).
<button (click)="openMyDialog()">Open My Dialog</button>
The same technique can be used for the dialog's show() and close() functions.
If you're up for doing everything manually, you can place a partially transparent grey DIV over everything on the page, then a single DIV on top of it with your dialog. Toggle visibility with JS/CSS, and you're able to style any way you like it.
Here's a quick example, with a significant need for improved styling:
div.greyModal {
opacity: 0.7;
background-color: grey;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
div.modalContent {
opacity: 1;
position: fixed;
width: 75%;
left: 50%;
margin-left: -37.5%;
height:100px;
background-color: white;
border: solid 4px black;
border-color: black;
}
<div>
This is the web page content. <span style="color:red">This is red text that appears faded when the modalToggle divs are visible</span>
</div>
<div class="greyModal modalToggle">
</div>
<div class="modalContent modalToggle">
This is the content of my modal dialog
</div>

how to prevent focus on any button, input, etc on a div?

I have a div which is a container of various things. Sometimes it contains some simply tables, and other layout stuff. But sometimes it contains buttons and forms.
This container div can show another div modally. Which I achieved by simply making its position: absolute, and have its top/bottom/left/right 0.
It looks nice but when I press the tab button focus can go to the elements on the div behind. How can I prevent this?
I know I can disable focus on one element by setting tabIndex=-1 so I could iterate however when the modal disappears I would need to restore all this elements. Which means extra work. I wonder if there is a general way of doing this with jQuery or maybe jqueryui or vanilla js?
EDIT:
Working example in jsbin:
https://jsbin.com/veciju/1/edit?html,css,js,output
I am not sure what is the exact issue without the fiddle, and did not check the code. But here is my solution (pure javascript) hope it helps
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="container">
<p id="filler">
Hello World.
</p>
<form id="myForm">
<input type="text" />
<input type="submit" value="submit"/>
</form><br>
<button id="openModal" onclick="openModal();"> Open Modal</button>
<div id="modal" class="hidden">
<p id="modelP"> This is a modal DIV. You cannot escape me</p>
<button id="closeModal" onclick="closeModal();">Close Me</button>
</div>
</div>
</body>
<style>
#container{
margin: 50px auto;
padding: 100px;
color: white;
width: 50%;
height:400px;
background-color: black;
text-align: center;
}
.hidden{
display: none;
}
#modal{
background-color: green;
border: 5px solid red;
z-index: 100;
width:80%;
height: 80%;
left: auto;
}
</style>
<script>
function openModal(){
var modalElement = document.getElementById('modal');
var others = document.querySelectorAll('* :not(#closeModal) ');
modalElement.removeAttribute('class');
for (i=0; i<others.length;i++){
console.log(others[i]);
others[i].setAttribute('disabled','disabled');
}
}
function closeModal(){
var modalElement = document.getElementById('modal');
var others = document.querySelectorAll('* :not(#closeModal) ');
modalElement.className='hidden';
for (i=0; i<others.length;i++){
console.log(others[i]);
others[i].removeAttribute('disabled');
}
}
</script>

How can I log information without using alert in userscripts

i have an userscript which traces all the dynamically created tags in javascript of a webpage. the problem here is presently i am using alert box to dispaly the output. The problem with alert() is that it can be very obtrusive. For every alert, you need to click the OK button to proceed which wastes your time. so i want an alternative method like log files other than alert box. how can i do this.
i am restricted to use console.log
I would use some kind of console element statically placed on your page which can be hidden if necessary. See this jsFiddle.
HTML:
<div id="console">
<div class="header">
Console
<span class="expand" onclick="toggleConsole();">+</span>
</div>
<div class="content" style="display: none;"></div>
</div>
CSS:
#console {
position: fixed;
right: 0px;
bottom: 0px;
width: 300px;
border: solid 1px #dddddd;
}
#console .header {
background-color: #ededed;
border: solid 1px #dddddd;
}
#console .header .expand {
padding-right: 5px;
float: right;
cursor: pointer;
}
#console .content {
overflow: auto;
background-color: #F9F9F0;
width: 100%;
height: 180px;
}
Javascript:
function log(text) {
var consoleContent = document.getElementById('console')
.getElementsByClassName('content')[0];
var line = document.createElement('div');
line.className = 'consoleLine';
line.innerHTML = text;
consoleContent.appendChild(line);
}
function toggleConsole() {
var content = document.getElementById('console')
.getElementsByClassName('content')[0];
if (content.style.display === "none") {
content.style.display = "block";
document.getElementById('console')
.getElementsByClassName('expand')[0].innerHTML = "-";
} else {
content.style.display = "none";
document.getElementById('console')
.getElementsByClassName('expand')[0].innerHTML = "+";
}
}
document.onload = function() {
document.getElementById('console')
.getElementsByClassName('expand')[0].onclick = toggleConsole;
};
Use log("some text"); to output to your console !
Install firefox add-on to your Mozilla(if you are using) and you the follwing code:
console.log("test"+your_variable);
So above code will display all logs in console.If IE press F12 and check console.
If a normal user should be able to see it, using the console is not a very user-friendly way.
Define a space on your webpage (a <div> might be handy) where you want the information to be, and just add the messages to that space using javascript (or jQuery) to modify the DOM:
HTML:
<div id='logmessages'>Log messages:</div>
JavaScript
function log(yourMsg) {
document.getElementByID('logmessages').innerHTML() += yourMsg;
}
It might be friendly to allow the user to show/hide the div with a button or another way.
Create a fixed div either at the top, bottom or corner of your page with set width/height and overflow auto, then insert the log entries in it.

Categories

Resources