how to add events as attribute to an element - javascript

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.

Related

Setting onclick function dynamically in Javascript not working

hello =) I am trying to create a heading tag with some text in it.
var d = document.createElement("h5");
d.innerHTML = "Dungeon";
and then assigning an onclick listener.
d.onclick = function(){myFunction()};
which doesn't seem to be working. I've also tried
d.onmousedown = function(){myFunction();};
and
d.onclick = "myFunction()";
and
d.addEventListener("mousedown", function(){myFunction});
and none of them seem to be working. I have thrown in a couple tracers around it, everything runs through fine without syntax errors but the actual element when appended to the document doesn't have the function tied to it at all. Would anyone happen to know why? Thanks in advance =)
Edit:
Here is a more detailed block of my code. Would this make any difference?
var x = document.createElement("ul");
var y = document.createElement("li");
x.appendChild(y);
var d = document.createElement("h5");
d.innerHTML = "Dungeon";
y.appendChild(d);
console.log(0);
d.onclick = function() { alert('test'); }
console.log(1);
elem.addEventListener("click", function, false);

how to blast ballons on click or touch in jquery

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>

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.

Jquery attr('src') undefined in IE 8 (works in FF)

This has gotten so far,that I will sum up what we found out:
Inside the event handler the attribute src cannot be read in IE8 (FF works fine), neither with jQuery nor with usual javascript
The only way to get the data was to get it outside the handler, write it to an array and read it afterwards from the inside of the handler
But there was still no possibility to write to src (neither jQuery nor javascript worked - only for IE 8)
I've got it working by writing the img elemts themselves to the document, but the reason behind this problem is no solved
The snippet we have is used twice.
The old code
<script type="text/javascript">
jQuery(document).ready(function() {
//...
//view entry
jQuery('.blogentry').live('click',function(){
// Get contents
blogtext = jQuery(this).children('.blogtext').html();
blogauthor = jQuery(this).children('.onlyblogauthor').html();
blogtitle = jQuery(this).children('.blogtitle').html();
profileimage = jQuery(this).children('.profileimage').html();
imgleft = jQuery(this).children('.Image_left').attr('src');
imgcenter = jQuery(this).children('.Image_center').attr('src');
imgright = jQuery(this).children('.Image_right').attr('src');
// Write contents
jQuery('#bild_left').attr('src', imgleft);
jQuery('#bild_center').attr('src', imgcenter);
jQuery('#bild_right').attr('src', imgright);
jQuery('.person').attr('src', profileimage);
jQuery('#g_fb_name').html(blogauthor);
jQuery('#g_titel').html(blogtitle);
jQuery('#g_text').html(blogtext);
//...
});
//...
// Change entry
jQuery('.blogentry').each(function(){
entryindex = jQuery(this).attr('rel');
if (entry == entryindex)
{
// The following works fine (so 'children' works fine):
blogtext = jQuery(this).children('.blogtext').html();
blogauthor = jQuery(this).children('.onlyblogauthor').html();
blogtitle = jQuery(this).children('.blogtitle').html();
profileimage = jQuery(this).children('.profileimage').html();
// This does not work - only in IE 8, works in Firefox
imgleft = jQuery(this).children('.Image_left').attr('src');
imgcenter = jQuery(this).children('.Image_center').attr('src');
imgright = jQuery(this).children('.Image_right').attr('src');
//alert: 'undefined'
alert(jQuery(this).children('.Image_center').attr('src'));
//...
}
}
//...
});
</script>
The new code
Please see my own posted answer for the new code.
UPDATE:
This does not work if called inside of the click event!!!
jQuery('.Image_left').each(function(){
alert(jQuery(this).attr('src'));
});
SOLUTION TO GET THE IMAGE DATA:
relcounter = 1;
imgleft_array = new Array();
jQuery('.Image_left').each(function(){
imgleft_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
relcounter = 1;
imgcenter_array = new Array();
jQuery('.Image_center').each(function(){
imgcenter_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
relcounter = 1;
imgright_array = new Array();
jQuery('.Image_right').each(function(){
imgright_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
//... inside the eventhandler (entryindex = 'rel' of blogentry):
imgleft = imgleft_array[entryindex];
imgcenter = imgcenter_array[entryindex];
imgright = imgright_array[entryindex];
This works because it is not called inside the event handler and the sources are saved beforehand
BUT! I still cannot write the data, which is my aim:
jQuery('#bild_left').attr('src', imgleft);
jQuery('#bild_center').attr('src', imgcenter);
jQuery('#bild_right').attr('src', imgright);
UPDATE!!!
This is just crazy, I tried to write the data via usual javascript. This also works in FF, but no in IE8. Here really is some serious problem witt the attribute src:
document.getElementById('bild_left').src = imgleft;
document.getElementById('bild_center').src = imgcenter;
document.getElementById('bild_right').src = imgright;
alert(document.getElementById('bild_left').src);
This works in FF, but not in IE8, the attribute src remains undefined after writing! This seems to be not a jQuery problem at all!
children looks for immediate child elements only where as find looks for all the elements within it until its last child element down the dom tree. If you are saying find is working that means the element you are looking is not its immediate children.
Try to alert this jQuery(this).children('#Image_center').length see what you get.
FYI. Even when any element is not found jQuery will return an emtpy object it will never be null. So alert an emtpy object will always give you [object Object]. You should alwasy check for the length property of the jQuery object.
Try this
alert(jQuery(this).find('#Image_center').length);//To check whether element is found or not.
Bing Bang Boom,
imgright = jQuery(".Image_right",this).attr('src');
And why don't you easily use one working?
alert(jQuery(this).children('#Image_center').attr('src'));
change children to find
alert(jQuery(this).find('#Image_center').attr('src'));
It is probably the easiest solution, and when it work, why wouldn't you use it?
the problem is not in the attr('src') but in something else. The following snippet works in IE8:
<img id="xxx" src="yrdd">
<script type="text/javascript">
alert($('#xxx').attr('src'));
</script>
But if you for example change the the text/javascript to application/javascript - this code will work in FF but will not work in IE8
This has gotten so far,that I will sum up what we found out:
Inside the event handler the attribute src cannot be read in IE8 (FF works fine), neither with jQuery nor with usual javascript
The only way to get the data was to get it outside the handler, write it to an array and read it afterwards from the inside of the handler
But there was still no possibility to write to src (neither jQuery nor javascript worked - only for IE 8)
I've got it working by writing the img elemts themselves to the document, but the reason behind this problem is no solved
The new code
relcounter = 1;
imgleft_array = new Array();
jQuery('.Image_left').each(function(){
imgleft_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
relcounter = 1;
imgcenter_array = new Array();
jQuery('.Image_center').each(function(){
imgcenter_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
relcounter = 1;
imgright_array = new Array();
jQuery('.Image_right').each(function(){
imgright_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
//view entry
jQuery('.blogentry').live('click',function(){
// Get contents
entryindex = jQuery(this).attr('rel');
blogtext = jQuery(this).children('.blogtext').html();
blogauthor = jQuery(this).children('.onlyblogauthor').html();
blogtitle = jQuery(this).children('.blogtitle').html();
profileimage = jQuery(this).children('.profileimage').html();
imgleft = imgleft_array[entryindex];
imgcenter = imgcenter_array[entryindex];
imgright = imgright_array[entryindex];
// Write contents
jQuery('#entryimages').html('');
jQuery('#entryimages').html('<img class="rotate" width="132" height="138" id="bild_left" src="'+imgleft+'" /><img class="rotateright" width="154" height="162" id="bild_center" src="'+imgcenter+'" /><img class="rotate" width="132" height="138" id="bild_right" src="'+imgright+'" />');
jQuery('.person').attr('src', profileimage);
jQuery('#g_fb_name').html(blogauthor);
jQuery('#g_titel').html(blogtitle);
jQuery('#g_text').html(blogtext);
});
So I am just not using .attr('src') in the event handler....
Try to make a delay:
jQuery(document).ready(function() {
setTimeout(function () {
jQuery('.blogentry').each(function(){
// your code...
});
}, 100); // if doesn't work, try to set a higher value
});
UPDATE
Hope, this code will work.
$('.blogentry img').each(function(){
alert( $(this).attr('src') );
});
UPDATE
I'm not sure, but maybe IE can't read classes with uppercase first letter...
Try to change ".Image_center" to ".image_center"
UPDATE
Check your code again. You definitely have some error. Try this jsfiddle in IE8, attr('src') is showed correctly. http://jsfiddle.net/qzFU8/
$(document).ready(function () {
$("#imgReload").click(function () {
$('#<%=imgCaptcha.ClientID %>').removeAttr("src");
$('#<%=imgCaptcha.ClientID %>').attr("src", "Captcha.ashx");
});
});

Categories

Resources