On a page, Save button should be visible or hidden based on system time.
I want to hide Save button everyday after 10 AM.
My broken code
<script type="text/javascript">
var currentTime = new Date();
var hours = currentTime.getHours();
var newButton = document.getElementById("btn1");
if(hours>10) {
newButton.style.display = "none";
//tried this one too
// document.getElementById('btn1').style.visibility = 'hidden';
}
else {
newButton.style.display = "block";
}
</script>
In HTML code I added
<input id="btn1" type="button" value="Save" name="btnSave" onclick="javascript: {ddwrt:GenFireServerEvent('__commit')}" />
Any suggestion or help.
Your function can be really simple, e.g.:
window.addEventListener("load", function(){
var newButton = document.getElementById("btn1");
newButton.style.visibility = new Date().getHours() > 10? 'none' : '';
});
Note that the default display value for buttons is inline-block, but not all browsers will necessarily use that and CSS may be used to set it to some other value. Setting the display to "" (empty string) lets it adopt its default or inherited style for the particular browser or style sheet and you don't have to change your code very time the page designer changes her/his mind.
Also, to really disable the button, you should set it's disabled property to true.
Wrap it in a onload event. Your button isn't on the page yet. An element that isn't rendered yet cannot be addressed.
window.addEventListener("load", function(){
var currentTime = new Date();
var hours = currentTime.getHours();
var newButton = document.getElementById("btn1");
if(hours>10) {
newButton.style.display = "none";
}
else {
newButton.style.display = "block";
}
}, false);
This way it fires when the page is loaded and the button in question is present.
Or like Deef commented, put the script tag on the bottom of your page.
Related
I would like to increase the font size of the paragraph as well as the font size of the number in the button.
I copied and pasted my sizer function from StackOverflow (a few alterations) and thought it would work and still can't get it to work. Can someone help?
Since I've spent so much time on just the first part, as a beginner programmer, I'm wondering what I am missing. Does anyone have any ideas from my code or their experience as to what I might be missing?
Thanks as always.
<html>
<button onclick='incrementer(); sizer()' id='count' value=0 />0</button>
<p id='test'>a</p>
<script>
clicks = 0
incrementer = function () {
clicks += 1
click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
}
sizer = function changeFontSize() {
div = document.getElementById("test");
currentFont = div.style.fontSize.replace("pt", "");
div.style.fontSize = parseInt(currentFont) + parseInt(clicks) + "pt";
}
</script>
</html>
Some things here:
I woudn't append two functions to your onclick here. Just append one and call your second function from the first one that gets fired via onclick. That looks a lot more tidy
Don't forget to put var before every variable, without it's not valid JavaScript
I didn't quite understand what you tried with your currentFont variable, so I removed it. It's not necessary and causes the script to not working correctly
<html>
<button onclick='incrementer()' id='count' value=0 />0</button>
<p id='test'>a</p>
<script>
var clicks = 0;
var incrementer = function() {
clicks += 1;
var click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
sizer();
}
var sizer = function changeFontSize() {
var div = document.getElementById("test");
div.style.fontSize = parseInt(clicks) + "pt";
}
</script>
</html>
Here's a from-scratch version that does what you're asking for. I'll point out a few things that I did to help you out.
https://codepen.io/anon/pen/VBPpZL?editors=1010
<html>
<body>
<button id="count">0</button>
<p id="test">
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</p>
</body>
</html>
JS:
window.addEventListener('load', () => {
const button = document.querySelector('#count');
const paragraph = document.querySelector('#test');
const startingFontSize = window.getComputedStyle(document.body, null)
.getPropertyValue('font-size')
.slice(0, 2) * 1;
let clicks = 0;
button.addEventListener('click', () => {
clicks++;
// this is a template literal
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const fontSize = `${startingFontSize + clicks}px`;
button.innerHTML = clicks;
button.style.fontSize = fontSize;
paragraph.style.fontSize = fontSize;
});
});
The code runs when the page is loaded, so we attach an event listener on the window object listening for the load event.
We then store references to the button and the paragraph elements. These are const variables because their values won't change. This also limits their scope to the containing function.
We get the initial font size for the body element, because in this example we aren't explicitly setting a base font in css so we're just using the one for the document. getComputedStyle is a somewhat expensive operation, and in this case we only need to get it in the beginning because it won't change, so we also store it as a const. The value is returned as a string like "16px" but we need the number, hence the slice and multiplying by one to cast the string into a number. parseInt would also do the same thing.
Notice that clicks is defined with let. This means that the variable can be changed. var still works of course, but in modern practices its best to use const and let when declaring variables. This is partly because it forces you to think about what kind of data you're working with.
We add an event listener to the button element and listen for the click event. First, we increment the clicks variable. Then we declare fontSize using a template literal which adds our new clicks count to the startingFontSize and "px" to get a string.
Finally, the innerHTML value of the button element is updated. Then we update the fontStyle property for both elements.
The issue here is that there is no initial value for the fontSize of your <p> tag so div.style.fontSize returns an empty string.
You can use window.getComputedStyle instead of div.style.fontSize and you will get the current fontSize.
There is already a post explaining this method
https://stackoverflow.com/a/15195345/7190518
You don't have an initial font-size style on your <p> tag, so it div.style.fontSize is always empty. Also, best practice is to always use var when introducing new variables in javascript.
One good trick to help debugging things like these is to use console.log() at various points, and see whats coming out in your browser console. I used console.log(div.style.fontSize) and the answer became clear.
Working below after adding <p style='font-size:12px'>a</p>:
<html>
<button style='font-size:12px;' onclick='incrementer(); sizer()' id='count' value=0 />0</button>
<p id='test' style='font-size:12px;'>a</p>
<script>
var clicks = 0
incrementer = function () {
clicks += 1
click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
}
var sizer = function changeFontSize() {
var div = document.getElementById("test");
var btn = document.getElementById("count");
var newSize = parseInt(div.style.fontSize.replace("pt", "")) + parseInt(clicks);
div.style.fontSize = newSize + "pt";
btn.style.fontSize = newSize + "pt";
}
</script>
</html>
I don't understand the logic of this solution, but you can simplify it avoiding to use a lot of var (anyway always prefer let or const if you don't need to change), using a single function and writing less code.
function increment(e){
const ctrl = document.getElementById('test');
let current = parseInt(e.dataset.size);
current += 1;
e.innerHTML = current;
e.dataset.size = current;
ctrl.style.fontSize = current + 'pt';
}
<button onclick="increment(this);" data-size="20">20</button>
<p id='test' style="font-size:20pt;">A</p>
I'm rendering balloons on-screen 20 times, from an array of images, and I want em to blast on-click.
I have really no idea how to do that.
I have gone through the jquery method ".hide" with click event but that didn't happen.
I am sharing a plunker.
Thank you in advance!
my plunker:-
https://plnkr.co/edit/P27tZS4tBt18Kw2fOPZv?p=preview
From what I read of your question you are just looking for a way to remove elements that have been added. Try something like this though you can replace the click button to create button feature with your timer:
<button onclick="createButton()">Try it</button>
<script>
var btnCount = 0;
var createButton = function(){
var button = document.createElement('button');
button.innerHTML = 'balloon';
button.setAttribute("id", "newbtn" + btnCount);
var btnNumber = 'newbtn'+btnCount;
button.onclick = function(){
document.getElementById(btnNumber).style.display = 'none';
};
document.body.appendChild(button);
btnCount++;
};
</script>
I have no clue what I'm doing wrong. It works it just shows the popup for a split second. Would a timeout option be better? Which part is the problem? I'm a little new to Javascript so I don't really know what to exactly look for.
<script language="javascript" type="text/javascript">
/** Create a html cookie and set expiry as a day. **/
function createCookie(name,value,days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = date.toGMTString();
document.cookie = name+"="+value+"; expires="+expires+"; path=/";
}
/** Check if already a cookie has been created. **/
function readCookie(name) {
var flag = 0;
var dcmntCookie = document.cookie.split(';');
for(var i=0;i < dcmntCookie.length;i++) {
var ck = dcmntCookie[i];
while (ck.charAt(0)==' ') {
ck = ck.substring(1,ck.length);
}
if(ck) {
cparts = ck.split('=');
if (cparts[0] == name) flag=1;
}
}
if(flag) {
return true;
} else {
return false;
}
}
/** Check if cookie exists else create a new one. **/
function checkCookie(name) {
if (readCookie(name)) {
document.getElementById('google').style.display = "none";
document.getElementById('google').style.visibility = "hidden";
}
else createCookie(name,"cookie 4 the day",1);
}
</script>
<script type="text/javascript">
function closeThisDiv()
{
var openDiv = document.getElementById('google');
openDiv.style.display = 'none';
}
</script>
<body onLoad="checkCookie('MyCookie')"
If your goal is to have the element with id="google" to be hidden from the very beginning of the page display (so it never shows), then you should add a CSS rule that loads in the head section like this:
#google {display: none;}
Or, you should add a style element to the HTML itself:
<div id="google" style="display:none"></div>
As your code is currently written, it sounds like it is doing what it is supposed to. It waits for the entire document to be loaded (including images) and then it hides the element with id="google". That means the item will show briefly while the page is loading and then your code will hide it.
If you can't modify the CSS or the HTML for the google object and you're just trying to hide it as soon as possible with javascript and the google object is present in the HTML of your page (not added programmatically), then you can do this:
<body>
other HTML here
<script>
// script that executes right before the /body tag
checkCookie("MyCookie")
</script>
</body>
This will at least not wait for all images to load before hiding it.
I fixed it like this:
Create a css property of display:none; for #google
#google{display:none;}
Then switch around the last portion of code to display only if they don't have the cookie, and to create the cookie.
/** Check if cookie exists else create a new one. **/
function checkCookie(name) {
if (readCookie(name)) {
}
else document.getElementById('google').style.display = "inline";
document.getElementById('google').style.visibility = "visibility";
createCookie(name,"cookie 4 the day",1);
In case anyone runs into this problem. Worked great for me.
Scenario:
User enters text "thisisabutton" for ButtonA
User enters text "thisisalongerbutton" for ButtonB
Both buttons dynamically adapt in size to fit text length, thus making them 2 different sizes
I want ButtonA to be the same size as ButtonB (which will determine the size since it's longer than ButtonA).
What is the best approach to do this in Javascript?
<button id="ButtonA" onChange="ResizeButtons();">Hello</button>
<button id="ButtonB" onChange="ResizeButtons();">Worlddddddddddddddd</button>
<script type="text/javascript">
function getWidth(element) {
return parseInt(window.getComputedStyle ? window.getComputedStyle(element,null).getPropertyValue("width") : element.currentStyle.width );
}
function ResizeButtons() {
var buttonA = document.getElementById("ButtonA");
var buttonB = document.getElementById("ButtonB");
buttonA.style.width = "auto";
buttonB.style.width = "auto";
var buttonAWidth = getWidth(buttonA);
var buttonBWidth = getWidth(buttonB);
var maxWidth = (buttonAWidth > buttonBWidth ? buttonAWidth: buttonBWidth) + "px";
buttonA.style.width = maxWidth;
buttonB.style.width = maxWidth;
}
</script>
1) Cross Browser.
2) Resets elements to "auto" before computing, or else they'll never resize after the first character is entered.
3) Avoids re-accessing DOM after getting buttonA and buttonB.
4) Checks while each button is being modified.
EDIT
You may have to put the ResizeButtons(); event on the inputs you're using to change the button content, or better yet, simply run the function ResizeButtons() inside your current script that changes the button content, immediately after the content is changed.
<button id="ButtonA">Hello</button>
<button id="ButtonB" onChange="ResizeButtons();">Worlddddddddddddddd</button>
<script type="text/javascript">
function ResizeButtons()
{
var buttonAWidth = document.getElementById("ButtonA").style.width;
var buttonBWidth = document.getElementById("ButtonB").style.width;
var maxWidth = 0;
if (buttonAWidth >= buttonBWidth){
maxWidth = buttonAWidth;
}
else{
maxWidth = buttonBWidth;
}
document.getElementById("ButtonA").style.width = maxWidth;
document.getElementById("ButtonB").style.width = maxWidth;
}
</script>
While this answer utilizes jQuery the principles are the same as the above answers without a lot of the extra hassle of handling getting a true element width. I by no means am advocating that you should necessarily use jQuery, but I think it illustrates the solution in a more concise fashion.
The user adds a new button by providing a new name.
Calculate the longest button and reset the widths of smaller buttons
The code:
<label for="buttonName">Enter Button Name:</label><input id="buttonName">
<button id="createButton">Create Button</button>
<div id="buttons"></div>
<script type="text/javascript">
$('#createButton').button().click(function(){
var buttonName = $('#buttonName').val();
$('#buttonName').val("");
$('#buttons').append($('<button>'+buttonName+'</button>').button());
var widestButton = 0;
$('#buttons button').each(function(){
widestButton = Math.max($(this).width(), widestButton);
});
$('#buttons button').width(function(){
if ($(this).width() < widestButton)
$(this).width(widestButton);
});
});
</script>
http://jsfiddle.net/PwNUA
I am trying to write a PHP Java Script, but struggling to write in this section of coding.
I am trying to make a buttom in form in that opens
The code I have written so far is
function display(e){
if (e.clicked)
document.getElementById('2').style.display = 'none';
else
document.getElementById('2').style.display = 'block';
and the FORM CODE is;
<input type="button" value=" Book Now " onClick="display(this)"/></input>
any help to point out my clear mistakes would be great, the live code can be seen at
http://affordablecleaners.co.uk/quote/
Thanks,
Henry
Try something similar to the following
var i = 0;
var display = function() {
document.getElementById('2').style.display = (i++ % 2) ? "none" : "block";
};
Essentially, we're creating a variable i and increasing it by one every time the function is called. If, when the function is called, i is an even number, then we set it to display: block. Otherwise, set it to display: none.
The biggest downside to this solution is cluttering the global scope. If this is an issue, you can also do the following.
var display = function() {
document.getElementById('2').style.display = (document.getElementById('2').style.display == "none") ? "block" : "none";
};
Here's the (untested) logic...
function display(state, which){
if (state==1) {document.getElementById(which).style.display ='none';}
else
{document.getElementById(which).style.display = 'block';}
}
and then in your button...
to turn ON
onclick="display('1',someDIV)"
to turn OFF
onclick="display('0',someDIV)"