AddEventListener function won't execute - javascript

The iFrameOn function runs on page load, and up until it is supposed to execute the iBold function is works fine. I've gone through and debugged as much as possible, and everything seems fine. When I output every variable to the console, the values are correct. It's just that one line (iBold(targetiFrame);) that won't run. I'm not sure what's going on.
function iFrameOn() {
var iFrames = document.querySelectorAll('form > iframe'); //Get all iframes in forms
var bolds = new Array(), italics = new Array(), underlines = new Array(), targetiFrame;
var getRT = document.getElementsByClassName('richText');
for (var rtIndex = 0; rtIndex < getRT.length;rtIndex++) { //Rich text event listeners
var rtid = getRT[rtIndex].id;
if (getRT[rtIndex].className == "richText bold") { //Bold text event listener
console.log('The id is: '+rtid);
bolds.push(rtid);
console.log('The bolds array contains: '+bolds);
} else if (getRT[rtIndex].className == 'richText underline') { //Underline text event listener
underlines.push(getRT[rtIndex]);
} else if (getRT[rtIndex].className == 'richText italic') { //Italic text event listener
italics.push(getRT[rtIndex]);
}
}
bolds.forEach(function(e, i, a) { //e = a[i]
console.log('e is '+e);
document.getElementById(e).addEventListener('click', function() {
console.log(e+' was clicked!');
targetiFrame = document.getElementById(e).getAttribute('data-pstid');
iBold(targetiFrame);
}, false);
});
}
function iBold(target) {
if (target == 0) {
document.getElementById('richTextField').contentDocument.execCommand('bold', false, null);
document.getElementById('richTextField').contentWindow.focus();
} else {
document.getElementById(target).contentDocument.execCommand('bold', false, null);
document.getElementById(target).contentWindow.focus();
}
}

I apparently had another iBold function in another js file

Related

Javascript Dynamically Created Event Handlers Disappear once another is added

I have an ordered list that I want to have items disappear from when clicked.
I have the following javascript code:
<script>
let halls = new Set();
function rm() {
halls.delete((this.id).substring(0,this.id.length-4));
document.getElementById(this.id).remove();
}
function setEventHandler(obj, name, fn) {
if (typeof obj == "string") {
obj = document.getElementById(obj);
}
if (obj.addEventListener) {
return(obj.addEventListener(name, fn));
} else if (obj.attachEvent) {
return(obj.attachEvent("on" + name, function() {return(fn.call(obj));}));
}
}
function addHall() {
let oldSize = halls.size;
let chosen = document.getElementById("hall2").value;
halls.add(chosen);
if (oldSize != halls.size) {
document.getElementById("fillHall").innerHTML += `<li id="${chosen}List" name="${chosen}" >${chosen}</li>`;
setEventHandler(chosen + "List", "click", rm);
}
};
document.getElementById("hall2").onchange = addHall;
</script>
Is there something I'm doing wrong?? How do I keep the event handler that will remove the list item?
I know my code is sloppy :/ sorry
Thanks

Handler defined with document.on deleted when object deleted from DOM

I have some severe memory leaks on my SPA. I managed to localize where the leak is, but I can't fix it. I have a code like this :
$(document).on("click.widget", ".glyphicon-collapse-down", function (e) {
var contentElement = $(e.target).closest(".widget").find(".widget-body");
$(e.target)
.removeClass("glyphicon-collapse-down")
.addClass("glyphicon-collapse-up");
kendo.fx(contentElement).expand("vertical").stop().play();
});
I can generate widgets over time on my single page, so I need the buttons to have a handler even if they don't exist yet (every widget come with a button group). When I switch from the current page to another, I delete everything from the page and load a new page with an ajax request. And here is appears the memory leak. I suspect that it might lies in the fact that the handlers are not deleted properly.
EDIT : The leak becomes very smaller when I don't include this script in the app :
//expand the widget
$(document).on("click.widget", ".glyphicon-collapse-down", function (e) {
var contentElement = $(e.target).closest(".widget").find(".widget-body");
$(e.target)
.removeClass("glyphicon-collapse-down")
.addClass("glyphicon-collapse-up");
kendo.fx(contentElement).expand("vertical").stop().play();
});
//collapse the widget
$(document).on("click.widget", ".glyphicon-collapse-up", function (e) {
var contentElement = $(e.target).closest(".widget").find(".widget-body");
$(e.target)
.removeClass("glyphicon-collapse-up")
.addClass("glyphicon-collapse-down");
kendo.fx(contentElement).expand("vertical").stop().reverse();
});
//remove the widget and updating the layout accordingly
$(document).on("click.widget", ".glyphicon-remove", function (e) {
var contentElement = $(e.target).closest(".widget");
var ancestor = $(contentElement).parent();
var rightColumn = $("#right-column");
var mainColumn = $("#main-column");
kendo.unbind(contentElement);
kendo.destroy(contentElement);
$(contentElement).fadeOut().remove();
// //Widget layout modification on remove
if ((rightColumn.items().length - 1 == 0) && (ancestor.attr("id") == "right-column")) {
if (mainColumn.items().length == 1) {
$("#main-column").removeClass("col-lg-6").hide().addClass("col-lg-12").fadeIn();
}
else if (mainColumn.items().length > 1) {
var firstWidget = mainColumn.items().last();
$(firstWidget).hide().prependTo("#right-column").fadeIn();
}
}
if ((mainColumn.items().length - 1 == 0) && (ancestor.attr("id") == "main-column")) {
if (rightColumn.items().length == 1) {
$("#right-column").removeClass("col-lg-6").hide().addClass("col-lg-12").fadeIn();
}
else if (rightColumn.items().length > 1) {
var firstWidget = rightColumn.items().last();
$(firstWidget).hide().prependTo("#main-column").fadeIn();
}
}
});
//Enable the widget fullscreen
$(document).on("click.widget", ".widget-fullscreen-on", function (e) {
var contentElement = $(e.target).closest(".widget");
contentElement.addClass("fullscreen");
$(e.target)
.removeClass("glyphicon-resize-full")
.removeClass("widget-fullscreen-on")
.addClass("glyphicon-resize-small")
.addClass("widget-fullscreen-off");
});
//Disable the widget fullscreen
$(document).on("click.widget", ".widget-fullscreen-off", function (e) {
var contentElement = $(e.target).closest(".widget");
contentElement.removeClass("fullscreen");
$(e.target)
.removeClass("glyphicon-resize-small")
.removeClass("widget-fullscreen-off")
.addClass("glyphicon-resize-full")
.addClass("widget-fullscreen-on");
});
//Inserts a widget into the page content and modifies the layout accordingly
function insertWidget(jtext) {
jtext.attr("id", "");
if (($('#main-column').items().length == 0) && ($('#right-column').items().length == 0)) {
if ($("#main-column").hasClass("col-lg-12")) {
$(jtext).hide().prependTo('#main-column').fadeIn();
}
else if ($("#right-column").hasClass("col-lg-12")) {
$(jtext).hide().prependTo('#right-column').fadeIn();
}
}
else if ($("#main-column").hasClass("col-lg-12")) {
$("#main-column").removeClass("col-lg-12").addClass("col-lg-6");
$(jtext).hide().prependTo('#right-column').fadeIn();
}
else if ($("#right-column").hasClass("col-lg-12")) {
$("#right-column").removeClass("col-lg-12").addClass("col-lg-6");
$(jtext).hide().prependTo('#main-column').fadeIn();
}
else if ($('#right-column').items().length < $('#main-column').items().length) {
$(jtext).hide().prependTo('#right-column').fadeIn();
}
else {
$(jtext).hide().prependTo('#main-column').fadeIn();
}
}

Javascript click event callback not working

I am using javascript to handle click event.
The code is below :
function addClickEventListenerToAllAnchorTag() {
var anchors = document.getElementsByTagName("a");
for(var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
var guid = anchor.attributes.getNamedItem('GUID');
if(guid)
{
anchor.addEventListener("click", onClickLoginPopup);
}
}
}
Here I am fetching all anchor tags that has GUID attribute and adding click event listener to it.
But my callback function onClickLoginPopup never gets called.
function onClickLoginPopup(e) {
console.log('onClickLoginPopup');
e.preventDefault();
var host = window.location.hostname;
var url = this.href;
var guid = this.attributes.getNamedItem("GUID");
var mainPopup = document.getElementById('popupMain');
var popupPayment = document.getElementById('popupPayment');
if( mainPopup == null ) {
console.log(mainPopup);
}
else if(userID)
{
showSocialLoginPopup();
return false;
}
if(popupPayment !== null){
showPaymentPopup();
}
//articleLinkClickAction(guid);
return false;
}
Calling Code:
function mpwInit() {
addPopupContents();
addClickEventListenerToAllAnchorTag();
}
includeScripts();
window.onload = mpwInit;
When are you calling addClickEventListenerToAllAnchorTag function ? Have you logged the list of selected anchor elements ? Is it an empty array ? If it is an empty array then you JavaScript code is getting executed before the page loads.

Listen for keyup on all input fields

Im trying to capture the keyup on all input fields on a page.
My current code is:
var els = document.querySelectorAll('input');
for (var i = 0; i < els.length; i += 1) {
addEvent('keyup', els[i], makeHandler(els[i]));
}
function makeHandler(field) {
console.log(field.value);
}
function addEvent(evnt, elem, func) {
if (elem.addEventListener) {
elem.addEventListener(evnt,func,false);
} else if (elem.attachEvent) {
elem.attachEvent("on"+evnt, function(e) {
e = e || window.event;
if (!e.preventDefault) {
e.preventDefault = preventDefaultOnIE;
}
func.call(this, e);
});
} else { // No much to do
elem[evnt] = func;
}
}
But for some reason its only capturing the value on page load, not once i begin to type in any of the fields.
Any ideas what I'm doing wrong?
The problem is with your makeHandler function. makeHandler(els[i]) is being evaluated and the return value (undefined, in this case) is being passed to addEvent as a handler. Try:
function makeHandler(field) {
return function() {
console.log(field.value);
};
}
This way, makeHandler(els[i]) will return a function that addEvent can then attach to keyup.
Alternatively, you could also just use:
function makeHandler() {
console.log(this.value); // 'this' will be the field that the event occurred on
}
and then use:
addEvent('keyup', els[i], makeHandler);
Side-note
I noticed a slight error in your code:
else { // No much to do
elem[evnt] = func;
}
I think you really want to set elem["on" + evnt] instead.
I like to embed the script in a function so I can minimize it in my IDE and turn it on and off globally. In other words, give it a name.
attachKeyupListenerToInputElements();
function attachKeyupListenerToInputElements(){
var inputs = doc.querySelectorAll('input');
for (var i = 0; i < inputs.length; i += 1) {
inputs[i].addEventListener("keyup", keyupHandler);
}
function keyupHandler() {
console.log(this.value);
}
}
Is this what you are looking for:
<script>
$(document).ready(function () {
$("input").keyup(function () {
alert("keyup");
});
});
</script>

JavaScript image at onload event

I am trying to load a new image every time the previously loaded image has finished loading.
The function create_photo_list works correctly. It creates an array of the photos that need to be loaded. If none need to be loaded then the array is empty. The problem is, when there are no more items to load the it keeps calling the load_next_photo function.
The reason I call the registerEventHandler every time in the function is because if I don't, the function is not called when the next photo loads.
function registerEventHandler(node, event, handler) {
if (typeof node.addEventListener == "function")
node.addEventListener(event, handler, false);
else
node.attachEvent("on" + event, handler);
}
// Remove an HTML element event handler such as onclick
// ex: unregisterEventHandler($("textfield"), "keypress", showEvent);
function unregisterEventHandler(node, event, handler) {
if (typeof node.removeEventListener == "function")
node.removeEventListener(event, handler, false);
else
node.detachEvent("on" + event, handler);
}
function load_next_photo() {
var loading_list = create_photo_list();
alert(loading_list.length);
if (loading_list.length > 0) {
img[loading_list[0]]['loaded'] = 1;
registerEventHandler($("load_img"), "onload", load_next_photo());
$("load_img").src = img[loading_list[0]]['img'];
}
else {
alert("nothing");
unregisterEventHandler($("load_img"), "onload", load_next_photo())
}
unregisterEventHandler($("load_img"), "onload", load_next_photo())
}
Can't get my head around what you currently have, but such code works just fine:
var _images = ["image1.jpg", "image2.jpg", "image3.jpg"];
var _index = 0;
window.onload = function() {
LoadImage();
};
function LoadImage() {
//stop condition:
if (_index >= _images.length)
return false;
var url = _images[_index];
var img = new Image();
img.src = url;
img.onload = function() {
_index++;
LoadImage();
};
document.getElementById("Container").appendChild(img);
}
This will add the images to the container (element with ID Container) one by one, live test case: http://jsfiddle.net/yahavbr/vkQQ7/
This is plain JS, feel free to ask about any part for elaboration. :)

Categories

Resources