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.
Related
I would like to fill a form from an array and then to remove that element from the array.
So when I click on the 'Fill It' button - form should be filled and now array should be without that element.
The Problem is that the array is not popped, shifted or sliced and it always loads the same data into form fields.
Html form I have:
<h3><input class="FormControl" placeholder="Discussion Title"></h3>
<textarea class="Composer-flexible" placeholder="Write something..." style="height: 166.2px;"></textarea>
My code:
var button = document.createElement("button");
button.innerHTML = "Fill It";
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
button.addEventListener ("click", function() {
var arr =
[["title1","post1"],["title2","post2"],["title3","post3"]];
var post = arr[0][1];
var title= arr[0][0];
document.getElementsByClassName("FormControl")[0].value=title;
document.getElementsByClassName("Composer-flexible")[0].value = post;
var arr=arr.slice(1);
console.log(arr);
});
Fiddle link:
https://jsfiddle.net/q1vc26oe/2/
After I fill it I have to review it a little bit and then I would submit it.
But problem occurs next time when I load html page and try to fill the same form but this time with 'title2' and 'post2' it loads 'title1' and 'post1' cause the array is not popped, shifted or sliced.How to do that?
In addition (it would be the next step when I make sure that script is running well) how to submit it, not automatically, but after 15 seconds cause I'd like to have a brief review before submitting (this is not big priority right now so you can add to your answer or not....)
This will be your working code: -
var button = document.createElement("button");
button.innerHTML = "Fill It";
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
var arr = [
["title1", "post1"],
["title2", "post2"],
["title3", "post3"]
];
button.addEventListener("click", function() {
var post = arr[0][1];
var title = arr[0][0];
document.getElementsByClassName("FormControl")[0].value = title;
document.getElementsByClassName("Composer-flexible")[0].value = post;
arr = arr.slice(1);
console.log(arr);
});
You were creating a new array (named 'arr') every time on button click, so make sure you create the array only once.
And make sure you check if the array is empty on button click
I'm making a Chrome extension that acts on Facebook's newsfeed. I'm trying to select the URL starting with "https://external-ort2-2.xx" from Facebook's "_q7o" div and log it to the console (function capturePic). The earlier code, which inserts a button after the "_q7o" div, works fine, so I think I'm selecting the right div. But URL isn't getting logged.
Many thanks!
function callAttentionToX(jNode) {
var uCW = jNode.closest("div._q7o");
var button = document.createElement("a");
button.innerHTML = "I'm a button";
button.style.float= "left";
uCW.append(button);
}
function capturePic(jNode) {
var uCW = jNode.closest("div._q7o");
var firstHref = $(".uCW a[href^='https://external-ort2-2.xx']").attr("href");
console.log(firstHref);
}
waitForKeyElements("[aria-label$='Story options']", callAttentionToX, capturePic);
I am currently creating a program which utilizes localStorage to create a site with a wishlist like functionality. However when I go to generate the html page that should create the wishlist with the photo of the item, the name and a button to remove said item from the list. But when I go to assign the onClick functionality to the button, the function fires on page load rather then on click. I have four main java script functions, one to add to the localstorage, one to remove from local storage, a helper function for removing and the one that will generate the wishlist page (where the problem is).
function genWishListPage(){
for (var i = 0; i < localStorage.length; i++) {
var item = getWishlist(i);
var name = document.createElement("p");
var removeButton = document.createElement("button");
var image = document.createElement("img")
image.src = item.image;
removeButton.innerText = "Remove from wishlist";
removeButton.onClick = RemoveFromWishList(item.name);
removeButton.setAttribute("ID","remove");
name.innerText = item.name;
document.body.appendChild(image);
document.body.appendChild(name);
document.body.appendChild(removeButton);
document.body.appendChild(document.createElement("BR"));
//removeButton.setAttribute("onclick", RemoveFromWishList(item.name));
//removeButton.addEventListener('click', RemoveFromWishList(item.name));
//document.getElementById("remove").addEventListener("click",RemoveFromWishList(item.name));
}
}
The commented parts are ways I have already tried and gotten the same bug.
Any help or advice is appreciated.
When you write
removeButton.onClick = RemoveFromWishList(item.name); you are assigning the return value of the function call to the onClick event. Instead you can write
removeButton.onClick = function() { RemoveFromWishList(item.name);}
You should assign a function to the onClick event listener.
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>
first, the prototype:
function Notification (title, message, id) {
var $title = this.title = title;
var $message = this.message = message;
var $id = this.id = title;
/* ---------------creating HTML prototype */
var $mainDiv = $("<div></div>").appendTo($("#wrapper"));
$mainDiv.attr('id', $id);
$mainDiv.addClass('main-div');
var $dismissButton = $("<button>X</button>").appendTo($mainDiv);
$dismissButton.attr('id', 'dismissButton');
var $pTitle = $("<h2></h2>").appendTo($mainDiv);
$pTitle.attr('id', 'title');
$pTitle.text($title);
var $para = $("<p></p>").appendTo($mainDiv);
$para.attr('id', 'message');
$para.text($message);
var $ul = $("<ul></ul>").appendTo($mainDiv);
var $li1 = $("<li></li>").appendTo($ul);
$li1.attr('id', 'okButton');
var $button = $("<button>Ok</button>").appendTo($li1);
$button.addClass('buttons');
/* ---------------Dismissing notifications */
$("#dismissButton").click(function() {
document.getElementById($id).remove();
});
};
So, the prototype is made using new Notification(*arguments here*) and there we get a box with a notification widget. so far so good.
when i press the X button (id dismissbutton) it should remove the box, and it does.
However. if i use the new notification several times i get several boxes (with different ids for the $mainDiv) with their dismiss buttons not working. the upmost widget box's dismiss button is the only one that works, and it deleted all the other boxes as well.
I need to seperate them and have the dismiss button working for each box seperately.
thanks in advance :)
The problem here is that you are creating multiple elements with the same ID (which is invalid HTML by the way).
Every time your run
var $dismissButton = $("<button>X</button>").appendTo($mainDiv);
$dismissButton.attr('id', 'dismissButton')
A new "dismiss button" is being created, which has the same ID (dismissButton) with the previous "dismiss buttons" (if any).
The other thing is that every time you run
$("#dismissButton").click(function() {
document.getElementById($id).remove();
});
You instruct only the first "dismiss button" to remove the element identified by the ID $id when clicked.
In my opinion the best way to fix this is by using references to the elements themselves and not IDs.
So I would make the creation of the dismiss button like this;
var $dismissButton = $("<button>X</button>").appendTo($mainDiv);
And determine its click callback like this
$dismissButton.on('click', function () {
$mainDiv.remove();
});
This should work fine for you.
Last, but not least I would avoid giving the same ID to any elements, since it produces invalid HTML code. You are doing so in the following lines
$dismissButton.attr('id', 'dismissButton');
$pTitle.attr('id', 'title');
$para.attr('id', 'message');
$li1.attr('id', 'okButton');