how to blast ballons on click or touch in jquery - javascript

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>

Related

how to add events as attribute to an element

I have this code:
var elmnt = document.createElement("div");
elmnt.onclick = function () {
alert("hello");
}
at this time, elmnt.outerHTML is <div></div>.
But this is what I want to get:
<div onclick="alert('hello')"></div>
I really don't know what I'm looking for,
would you help me?
This worked for me:
var elmnt = document.createElement("div");
// var elmnt_text = document.createTextNode('click to see alert');
// elmnt.appendChild(elmnt_text);
elmnt.addEventListener('click', function(){
alert('hello')
})
document.body.appendChild(elmnt);
By commenting the two lines of code, you will see the div with its handler when you inspect element as in
<div onclick="alert('hello')"></div>
However, I wanted to be sure that it works so I dynamically created a text node for the div for testing purpose, and the click event fires as expected.
Hope this helps.

Dynamically increasing font size

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>

Hide button based on hours

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.

javascript delete file on unlimited upload button

thanks for the upcoming assistance, I am working on a uploader and trying to add a javascript delete link to each extra input field. I have one that adds a child.
here is a codepen: http://codepen.io/anon/pen/NPPmYP
What I am wanting to do is during creation of the extra input fields, Here is my code if anyone is able to help.
I also tried these methods and they didnt work
<script language="javascript">
<!--
function _add_more() {
files.appendChild(document.createElement("br"));
var del = document.createTextNode("Delete ");
document.getElementById("files").appendChild(del);
var extra = document.createElement('input');
extra.type="file";
extra.id="images[]";
extra.name="images[]";
extra.size="50";
extra.accept="image/jpeg";
document.getElementById("files").appendChild(extra);
}
</script>
I tried changing what I have for that line into
var del = document.createTextNode('delete ');
But it just showed it as text instead of making it a clickable link, I am really unsure on how to create the function to remove a child without effecting any others. Thank you for the upcoming support
You'll need to attach an event handler to the click of the delete link.
Something like this. (Updated as per comment)
<script language="javascript">
function _add_more() {
var del = document.createElement("a");
del.appendChild(document.createTextNode("Delete"));
del.href="#"; // Apply link styling
var extra = document.createElement('input');
extra.type="file";
extra.id="images[]";
extra.name="images[]";
extra.size="50";
extra.accept="image/jpeg";
var additionalFile = document.createElement('span');
additionalFile.appendChild(document.createElement("br"));
additionalFile.appendChild(del);
additionalFile.appendChild(extra);
document.getElementById("files").appendChild(additionalFile);
del.addEventListener('click', function(event){
additionalFile.parentElement.removeChild(additionalFile);
event.preventDefault();
});
}
</script>

addEventListener programmatically is null

var button = document.createElement("button");
button.type = "button";
button.className = "button";
button.innerText = "OK";
button.addEventListener("click", function () {
console.log("Hello!");
}, false);
When I do this, the button never gets that event listener. I've tried attachEvent, button.onclick, and nothing seems to work. The button shows up fine with the class and text.
EDIT: So basically what I'm trying to do is programmatically show a "popup" array of divs.
Here is a screenshot of what it looks like: http://i.imgur.com/IqaOq.png, and I set it up like this: var x = new JMTK.Custom.MessageDialog(), then to add a popup, I just type x.addMessage({template: {type: JMTK.Custom.MessageDialog.templates.alert, title: "Alert title", message: "This is a message here", button1: {text: "Hello"}}})
This is the addMessage():
var content = document.createElement("div");
//htmlObject.template is the object that has all the info, 'this' is the scrim element that contains each "white" popup"
content.innerHTML = MessageDialogClass.html.alert(htmlObject.template, this).innerHTML
which calls this function:
alert: function (template, element) {
//Array of functions
var callbacks = MessageDialogClass.callbacks;
var alert = document.createElement("div");
var id = Date.now();
alert.id = id;
var header = document.createElement("h1");
header.innerText = (template.title ? template.title : "ALERT");
var paragraph = document.createElement("p");
paragraph.innerText = (template.message ? template.message : "No message specified")
var button = document.createElement("button");
button.type = "button";
button.className = "button";
button.innerText = (template.button1.text ? template.button1.text : "OK");
button.addEventListener("click", function () {
if (template.button1.callback) {
template.button1.callback();
}
//MessageDialogClass.popElement(id);
//delete callbacks.id;
}, false);
alert.appendChild(header);
alert.appendChild(paragraph);
alert.appendChild(button);
callbacks.id = alert;
return alert;
},
But again, when I click on the button, nothing happens, and in the DOM Explorer there is no onclick attribute.
It's hard to say what your solution might be. You've provided good detail about what you want to do with the button click, but I'm afraid there's something else at play. I wonder if you have an element in front of the button that keeps it from receiving the mouse click. I see you're in a WinJS project for Windows 8. You have really good dev tools in VS2012. Break just after you add the button to your DOM and go to the DOM Explorer and see if you find the button. Go to the JavaScript Console and see if you can access the button. See if you can add an event listener manually there. Try adding the button manually in your markup and then see if adding an event works. Hope one of these gets you to the solution. Good luck.
The issue was that I was creating a div in my 'alert' template, and then setting the innerHTML of another div to that div. So it wouldn't allow me to set the event listener because it wasn't part of the DOM.
So instead of doing
var content = document.createElement("div");
//htmlObject.template is the object that has all the info, 'this' is the scrim element that contains each "white" popup"
content.innerHTML = MessageDialogClass.html.alert(htmlObject.template, this).innerHTML
I just did
var content = document.createElement("div");
//htmlObject.template is the object that has all the info, 'this' is the scrim element that contains each "white" popup"
content = MessageDialogClass.html.alert(htmlObject.template, this).innerHTML
because alert is returning a div already. So yeah, it had to do with setting the innerHTML rather than just setting it equal to the DOM node.
I think you need append your button before set the event listener.

Categories

Resources