Trying to make a popup javascript class - javascript

I am having trouble trying to do a click function inside the javascript class, "this.overlay.style.display = 'block'" not working due to "this" because "this" refers back to the click event i assume? what should i do to overcome this obstacle? i can console.log(options.overlay.id) outside of the click event, but inside the click event it will be undefined. what is the optimal solution for this?
var popup_overlay = document.getElementById("popup_overlay"),
update_coins = document.getElementById("update_coins");
// POPUP CLASS
var Popup = function (options) {
console.log(options.overlay.id); //THIS WORKS
this.overlay = options.overlay;
this.button = options.button;
this.button.addEventListener("click", function(e){
// this.overlay.style.display = 'block';
alert(e.target.getAttribute('data-popup'));
});
};
var popup_update_coins = new Popup(
{
overlay: popup_overlay,
button: update_coins
}
);

You could use Arrow function
// POPUP CLASS
var Popup = function(options) {
console.log(options.overlay.id); //THIS WORKS
this.overlay = options.overlay;
this.button = options.button;
this.button.addEventListener("click", (e) => { // Arrow function
this.overlay.style.display = 'block'; // this === Popup
alert(e.currentTarget.getAttribute('data-popup')); // currentTarget
});
};
var popup_overlay = document.getElementById("popup_overlay"),
update_coins = document.getElementById("update_coins");
var popup_update_coins = new Popup({
overlay: popup_overlay,
button: update_coins
});
#popup_overlay {
display: none;
}
<button id="update_coins" data-popup="TEST">update</button>
<div id="popup_overlay">asdasd</div>

Related

addEventListener('click') not working on a button to close a modal

So I have a modal that does not seem to want to close when clicking the close button. This what my current code looks like to show and close the modal as well as adding the modal-backdrop into the DOM and removing it.
const $ = document;
class Selectable {
addElement = () => {
const html = '<div class="modal-backdrop show"></div>';
const body = $.querySelector('body');
body.innerHTML += html;
};
removeElement = elementClass => {
let element = $.querySelector('.' + elementClass);
element.parentNode.removeChild(element);
};
showModal = () => {
const modal = $.getElementById('modal-finish');
const body = $.querySelector('body');
modal.classList.add('show');
body.classList.add('modal-open');
this.addElement();
};
closeModal = () => {
const modal = $.getElementById('modal-finish');
const body = $.querySelector('body');
modal.classList.remove('show');
body.classList.remove('modal-open');
this.removeElement('modal-backdrop');
};
init() {
// Look Up Button
$.getElementById('btn-look-up').addEventListener(
'click',
this.showModal,
false
);
// Close the Modal
$.querySelector('.modal-close').addEventListener(
'click',
this.closeModal,
false
);
}
}
const Selectables = new Selectable();
Selectables.init();
I have a feeling it's because the clickEvent is being registered straight away or something but I'm not completely sure.
Basically the modal opens but the close button is not functioning at all.
I've only ever used jQuery before to do JavaScript so I am using const $ = document; to ease the change over to standard JavaScript.
Try below Code:
Try it
document.getElementById("myBtn").addEventListener("click", function(){ document.getElementById("demo").innerHTML = "Hello World";
});

Setting Events in a class that utilize a later mentioned Prototype?

When I reach the console.log() its returning window.
How can I get the element under consideration?
let builder = function(){
this.box = $(`<div id="box" class="box">`);
this.inputcontainer = $(`<div id="inputcontainer" class="inputcontainer">`).appendTo(this.box);
this.textarea = $(`<textarea id="textarea"></textarea>`).appendTo(this.inputcontainer);
this.textarea.on("change keyup keydown input paste", this.postmsg);
this.chat.appendTo($('body'));
}
//someothercode
builder.prototype.postmsg = (e) => {
console.log(this); // returns window when I need it to be referencing textarea
}
let instance = new builder();
builder.prototype.postmsg = function(e){
console.log(this.textarea);
}

Toggle Event Listeners

I am trying to make a function that would allow me to toggle eventListener of an element.
In the example below, I have three buttons: main, on and off. When I click on the on button, the main button becomes functional. After I click off button, the main button should not work anymore (but now it still does).
Now I can achieve a desired behavior by clicking on button for the second time, but I guess it's a bad coincidence and it's not supposed to work that way.
Maybe I should add that I would like to work this out without using jQuery or similar and it needs to be a function, because I am going to use it for a lot of buttons.
(I suspect something with scope causes the problem (clickHandler when calling the function to activate the button is not the same as the clickHandler when calling the function to disable the button), but I can't think of a way to test it.)
// buttons definitions, not important
var mainButton = document.querySelector("#mainButton");
var onButton = document.querySelector("#onButton");
var offButton = document.querySelector("#offButton");
// main function
var toggleButtons = function(toggleVal, button, element) {
var activateButton, clickHandler, disableButton;
// callback function for listener bellow
clickHandler = function() {
document.querySelector(element).classList.toggle("yellow");
};
activateButton = function() {
button.addEventListener("click", clickHandler);
};
disableButton = function() {
button.removeEventListener("click", clickHandler);
};
// when first argument is 1, make the button functional, otherwise disable its functionality
if (toggleVal === 1) {
activateButton();
} else {
disableButton();
}
};
// when onButton is clicked, call main function with arguments
// this works
onButton.addEventListener("click", function() {
toggleButtons(1, mainButton, "body");
});
// this fails to disable the button
offButton.addEventListener("click", function() {
toggleButtons(0, mainButton);
});
.yellow {
background-color: yellow;
}
<button type="button" id="mainButton">mainButton
</button>
<button type="button" id="onButton">onButton
</button>
<button type="button" id="offButton">offButton
</button>
<p>mainButton: toggles background color on click
</p>
<p>onButton: turns on mainButtons's functionality</p>
<p>offButton: supposed to turn off mainButton's functionality</p>
var mainButton = document.querySelector("#mainButton");
var onButton = document.querySelector("#onButton");
var offButon = document.querySelector("#offButton");
var element; // declare the element here and change it from toggleButtons when needed.
function clickHandler() {
document.querySelector(element).classList.toggle('yellow');
}
function activateButton(button) { // You missed this part
button.addEventListener('click', clickHandler);
}
function disableButton(button) { // You missed this part
button.removeEventListener('click', clickHandler);
}
function toggleButtons(value, button) {
if (value === 1) {
activateButton(button); // You missed this part
} else {
disableButton(button); // You missed this part
}
};
onButton.addEventListener('click', function() {
element = 'body'; // you can change it to some other element
toggleButtons(1, mainButton);
});
offButton.addEventListener('click', function() {
element = 'body'; // you can change it to some other element
toggleButtons(0, mainButton);
});
Below code helps to toggle between two functions from an eventListener:
var playmusic=false;
function playSound() {
const audio = document.querySelector(`audio[data-key="${event.keyCode}"]`)
audio.currentTime = 0
audio.play()
playmusic=true;
}
function stopSound() {
const audio = document.querySelector(`audio[data-key="${event.keyCode}"]`)
audio.pause()
playmusic=false;
}
window.addEventListener('keydown',
function(){playmusic?stopSound():playSound()} )

Copy/Paste element with jQuery

I have a div that I'm appending to another div when a button is clicked. I'm also calling a bunch of functions on the div that gets created.
HTML
<a onClick="drawRect();">Rect</a>
JS
function drawRect(){
var elemRect = document.createElement('div');
elemRect.className = 'elem elemRect';
elemRect.style.position = "absolute";
elemRect.style.background = "#ecf0f1";
elemRect.style.width = "100%";
elemRect.style.height = "100%";
elemRect.style.opacity = "100";
renderUIObject(elemRect);
$('.elemContainer').draggableParent();
$('.elemContainer').resizableParent();
makeDeselectable();
handleDblClick();
}
var createDefaultElement = function() {
..
..
};
var handleDblClick = function() {
..
..
};
var renderUIObject = function(object) {
..
..
};
var makeDeselectable = function() {
..
..
};
I could clone the element when the browser detects a keydown event
$(window).keydown(function(e) {
if (e.keyCode == 77) {
$('.ui-selected').clone();
return false;
}
});
then append it to #canvas. But the problem is, none of the functions I mentioned above get called with this method.
How can I copy/paste an element (by pressing CMD+C then CMD+V) and call those above functions on the cloned element?
The jQuery.clone method returns the cloned node. So you could adjust your code to do something like this:
var myNodes = $('.ui-selected').clone();
myNodes.each(function () {
createDefaultElement(this);
appendResizeHandles(this);
appendOutline(this);
});

I need to access event context AND object context in event handler

I've this piece of code:
function ActivityDialog(_divId, _title) {
function addButton() {
var buttonElement = document.createElement('input');
buttonElement.setAttribute('type','button');
buttonElement.setAttribute('class','button');
buttonElement.setAttribute('id','updateButton-' + id););
buttonElement.onclick = this.updateAction;
};
function updateAction() {
var buttonId = this.id; // correct: this is the Button
this.sendUpdateRequest(stringUrl); // not defined: Need to reference the current ActivityDialog!!!
};
function sendUpdateRequest(url) {
// something...
};
}
As you can see the problem is when I call function sendUpdateRequest; how can I, at the same time, retrieve button infos and call a function?
You might try this...
function ActivityDialog(_divId, _title) {
// Store the ActivityDialog context
var self = this;
function addButton() {
var buttonElement = document.createElement('input');
buttonElement.setAttribute('type','button');
buttonElement.setAttribute('class','button');
buttonElement.setAttribute('id','updateButton-' + id););
buttonElement.onclick = this.updateAction;
};
function updateAction() {
var buttonId = this.id;
self.sendUpdateRequest(stringUrl); // <---------------------
};
function sendUpdateRequest(url) {
// something...
};
}
Because your using updateAction as a event handler, you correctly see that this will be the button that generates the event. Storing the initial context of the ActivityDialog will allow you to maintain access to it even within event handlers.

Categories

Resources