addEventListener Module Pattern - javascript

I don't know why but when I click on "button" nothing happens...
No message in console, no error. How to fix it ?
JS
var bird = (function(){
let button = document.querySelector('#addBird');
button.addEventListener('click', addBird);
function addBird()
{
console.log('addBird');
};
return {
addBird: addBird
};
})();
HTML
<button id="addBird">Add Bird</button>

Just tried this example in CodePen:
http://codepen.io/JasonGraham/pen/pbowXz
var bird = (function(){
let button = document.querySelector('#addBird');
button.addEventListener('click', addBird);
function addBird()
{
console.log('addBird');
};
return {
addBird: addBird
};
})();
As far as I can see, your code appears to be working as expected. In Chrome, clicking on the button causes the "addBird" message to be logged to the console each time.
Are you expecting something different?

This happens because the JavaScript loads before the DOM (basically, the HTML markup) is ready. Therefor, the button variable equals NULL.
Two ways to solve this:
Move your JavaScript at the end of the page, just before the </body> tag.
Wrap your JavaScript code with jQuery's document ready function:
$(function() {
// code here
});

Ok if I insert and outside the #birdMod It works... So it was not the .render() function. Thank you for your help. :)

Related

JavaScript and WordPress: button click not found by addEventListener

To prevent answers like: 'is the JavaScript file loaded?' -> Yes, it is loaded, at the footer part of the page! I have checked that with a simple message to the console, which is displayed!
But:
I've got a page with a button:
<button id="portfolio-posts-btn">Load portfolio related blog posts</button>
And a file main.js:
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
The text the button was clicked! should be displayed in the console, but it stays empty!
Apparently, the button click is not recognized, and thus, the var portfolioPostsBtn is false, or NULL... -> the method addEventListener() is not fired ?
I don't see the cause for this; I checked the spelling, should I use single or double quotes? Please help?
Thank you!
I've had this happen to me before, since theres two ways to do this I just used the other.
The first is onclick="function()", this is used as an attribute inside the element. Ex:
function clicked(){
alert("button clicked");
}
<button onclick="clicked();">Press me</button>
exaplaination: When you add this attribute to this element and I do believe some others when the button is clicked the specified code inside the quotes of the attibute will run. It doesn't have to be a number, e.g. onclick="alert(12+4/2);". But this is more of HTML than JavaScript using this version
The other way is using what you've got which (to me) is a lot more difficult then it needs to be. Heres my example
var b = document.getElementById("btn");
b.addEventListener("click", blogged);
function blogged(){
alert("this post has been blogged");
}
<button id="btn">Blog it</button>
This side of things has more to do with JavaScript and Event listeners. But the problem with you're code is that you're putting the event listener after you call the if statement. Here's my solution
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
portfolioPostsBtn.addEventListener("click", function(){
check();
});
function check(){
if(portfolioPostsBtn){
console.log("posted");
}
}
<button id="portfolio-posts-btn">press this to post<button>
Presumably you have made a decision not to use jQuery. You'll need to wrap your code in an event listener so that the code is executed when the DOM is ready.
document.addEventListener("DOMContentLoaded", function(event) {
var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
});
The answer is found in the uploading of the file page-portfolio.php!
I found out that the id="portfolio-posts-btn", added later, was not updated - could be my mistake, or the SFTP upload extension in Brackets - I did not see an error message!
Anyway, the issue is solved!
One more question: "are there methods to check if an id exists?". That could make live easier!
All contributors, thank you for your answers!

Polymer Selenium Test Accessing Sub-Element Data

In a firebase-login element I have
<paper-button id="btnLogin" data-dialog="login-modal" on-tap="toggleLogin">
<iron-icon icon="account-box"></iron-icon>
Login
</paper-button>
Where toggleLogin calls:
toggleLogin: function() {this.$.loginModal.toggle();},
In the Polymer test suite I am using:
Polymer.dom(element.root).querySelector('#btnLogin').click();
But Selenium is giving me the error of:
this.$.loginModal.toggle is not a function
Long story short, how can I click the button and check the modal pops up?
Note: Polymer team's test looks like:
Polymer.dom(myEl.root).querySelector('button').click()
Since they are naming their element myEl instead of element and looking for the button tag instead of the tag with id of btnLogin I felt that my solution was suitable. What am I doing wrong here?
UPDATE:
While looking at the bind event I still have not gotten things working.
CODE:
var btnLogin = Polymer.dom(myEl.root).querySelector('#btnLogin');
// This does the same thing as
// var btnLogin = element.$.btnLogin;
btnLogin.click.bind(btnLogin);
The above code allows me to move past the line but does not actually toggle the dialog. I am not sure why. When I add in click() instead of click it gives me the this.$.loginModal.toggle() is not defined error that I have been struggling with.
UPDATE:
Still have not found a good answer to this. Was looking into some code that may help and found the submenu element that wants to know information about it's content elements. I will include their testing below.
CODE:
suite('<paper-submenu>', function() {
var menu,
sub1, sub2, sub3,
collapse1, collapse2, collapse3,
trigger1, trigger2, trigger3;
setup(function() {
menu = fixture('basic');
sub1 = menu.querySelectorAll('paper-submenu')[0];
sub2 = menu.querySelectorAll('paper-submenu')[1];
sub3 = menu.querySelectorAll('paper-submenu')[2];
collapse1 = Polymer.dom(sub1.root).querySelector('iron-collapse');
collapse2 = Polymer.dom(sub2.root).querySelector('iron-collapse');
collapse3 = Polymer.dom(sub3.root).querySelector('iron-collapse');
trigger1 = sub1.querySelector('.menu-trigger');
trigger2 = sub2.querySelector('.menu-trigger');
trigger3 = sub3.querySelector('.menu-trigger');
});
test('selecting an item expands the submenu', function() {
assert.isFalse(collapse1.opened);
assert.isFalse(collapse2.opened);
assert.isFalse(collapse3.opened);
MockInteractions.tap(trigger1);
assert.isTrue(collapse1.opened);
assert.isFalse(collapse2.opened);
assert.isFalse(collapse3.opened);
});
Following the above example I tried the following:
test('Login Modal Opens', function(done) {
expect(loginModal).to.exist;
console.log(loginModal);
console.dir(loginModal);
expect(loginModal.opened).to.exist;
assert.isFalse(loginModal.opened);
btnLogin.click.bind(btnLogin);
assert.isTrue(loginModal.opened);
});
Unfortunately I am getting loginModal.opened as undefined. loginModal.toggle() gives toggle is not a function error.
UPDATE:
I found that bind does not actually call the function. It only binds the this to a new location. So when I was doing btnLogin.click.bind(btnLogin) it was doing the binding so when I called btnLogin.click() it would have a binding to btnLogin rather than ... btnLogin. Therefore it would have been the same to just call btnLogin.click() without ever calling the bind function.
Now that this is figured out, I decided to mess with call instead of bind but again I only was binding the this to the same scope so that was no help. I then tried btnLogin.click.call(element) but it still gave me the error that this.$.loginModal.toggle is not a function.
Just a wild guess, I don't know JS well
var el = Polymer.dom(element.root).querySelector('#btnLogin');
el.click().bind(el)();

Button.onclick automatically triggers, then will not trigger again

I have a script, which I'm using to try and display only one section of a webpage at a time.
function showMe(id){ clearPage(); changeDisplay(id, "block"); console.log(id)}
Currently, I'm using buttons to change which section is displayed.
var aBtn = document.getElementById("a-btn");
var otherBtn = document.getElementById("other-btn");
aBtn.onclick=showMe("a-btn-section-id");
otherBtn.onclick=showMe("other-btn-section-id");
However, when I load the page, the following happens:
I see the function attached to each button activate once in sequence in the console.
The page refuses to respond to further button inputs.
Testing with the console shows that showMe() and the functions it calls still all work properly. I'm sure I'm making a very basic, beginner mistake (which, hopefully, is why I can't find this problem when I Google/search StackOverflow/read event handling docs), but I'm at a loss for what that mistake is. Why would my script assume my buttons are clicked on load, and why won't it let me click them again?
You're calling the function an assign the value to onclick property instead of attach the function, try defining your onclick property as:
aBtn.onclick=function(){showMe("a-btn-section-id");};
otherBtn.onclick=function(){showMe("other-btn-section-id");};
Try the follow jsfiddle:
function showMe(id){ // some stuff..
console.log(id)
}
var aBtn = document.getElementById("a-btn");
var otherBtn = document.getElementById("other-btn");
aBtn.onclick=function(){showMe("a-btn-section-id");};
otherBtn.onclick=function(){showMe("other-btn-section-id");};
<input type="button" value="a-btn" id="a-btn"/>
<input type="button" value="other-btn" id="other-btn"/>
Hope this helps,

Javascript function not being run from click - what am I doing wrong?

I am currently making some accessibility options which make the font size increase or decrease on a page. Following EndangeredMassa's for calling JS from a link it appears not to work!
My current code (which is dummy code with the right IDs which will be used in my actual site), does not even run a Javascript alert, and since I'm not one for Javascript, if anyone could let me know what I'm doing wrong.
HTML
<p id="html">Nice to meet you!</p>
<a id="incFontS" href="#">Increase Text</a>
JavaScript
var incFont = document.getElementById("incFontS");
incFont.onClick = function () {
window.alert("it ran!");
}
As you can see from my jsfiddle, the code does not work at all, and I haven't even gotten to the part where I start changin the font sizes (geh!).
Any help is greatly appreciated!
Case matters in JavaScript. The correct property name is onclick (with a lowercase 'c'). Try this:
var incFont = document.getElementById("incFontS");
incFont.onclick = function () {
window.alert("it ran!");
}
Demonstration
Also, be sure to read addEventListener vs onclick for a discussion about different techniques for binding event listeners.
DEMO
var incFont = document.querySelector("#incFontS");
incFont.addEventListener('click', function () {
window.alert("it ran!");
return false;
});
The function name is onclick not onClick
i.e.
var incFont = document.getElementById("incFontS");
incFont.onclick = function () {
window.alert("it ran!");
}
works for me.
Try this way to do increase your font size
HTML CODE
<p id="html">Nice to meet you!</p>
<a id="incFontS" href="#" onclick="myFunction()">Increase Text</a>
Java Script Code
<script>
function myFunction() {
document.getElementById("html").style.fontSize="xx-large";
}
</script>

javascript events handlers don't work properly

I have some problem with javascript event handlers and I really want to know what am I doing wrong.
Here's the thing, I want to alert the hovered div's width, but as soon as the page is loaded, the alert appears.
Here's the HTML:
<div id="mainContainer">
<div id="container_1" style="width:200px"></div>
<div id="container_2" style="width:100px"></div>
<div id="container_3" style="width:300px"></div>
<div id="container_4" style="width:150px"></div>
</div>
and here's the js:
dataRetrieving = {
getWidth:function(id){
var box = document.getElementById(id);
var tempResult = box.style.width;
return tempResult;
}
}
var container = document.getElementById("container_1");
container.onmouseover = function(){
alert(dataRetrieving.getWidth("container_1"));
};
already answered, thanks :D
I'd appreciate any tip you guys give me.
Thanks in advance!
You would need to set your onmouseover with something like this:
container.onmouseover = function(){
dataRetrieving.getWidth("container_1");
};
In your current code, the event handler (set to container.onmouseover) is set to the result of dataRetrieving.getWidth(...) - which is nothing, since getWidth doesn't currently return anything. This is also causing the alert to appear immediately, since the function is executing immediately. (In order to be valid, it would have to return another function.)
container.onmouseover = dataRetrieving.getWidth("container_1");
You are calling that function there that's why it's alerting on the page load.

Categories