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,
Related
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!
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)();
TL;DR: Trying to fire a manual javascript click event on the chat button of twitch, won't send the message. Don't understand why the event doesn't do the same as a normal click and don't know how to make it work.
So I am trying to make a custom bot for twitch.tv, only reading his info from the HTML directly. I've got it perfectly working up to the point at where it can recognize commands and put text in the textbox. Now the problem I have is, as soon as I try to fire a manual click event on the "chat" button, it just doesn't seem to work. My guess is it has something to do with ember.js, and I frankly don't know anything about that. Anyway, here is the part of the code that doesn't work. EDIT: this works if I enter it as single in the console, doesn't work in context of the rest of my code though.
$('.send-chat-button').click();
What happens here is that I acquire a piece of html that contains the chat submit button, which is this:
<button class="button primary float-right send-chat-button" data-bindattr-3945="3945">
<span>
Chat
</span>
</button>
When I try to manually fire a click event on this, nothing happens. However, when I fire a manual click event on buttonContain.children[0] and buttonContain.children1 (which are, respectively, the settings and list of viewers buttons), it does work. They look like this:
<a data-ember-action="3943" class="button glyph-only float-left" title="Chat Settings"></a>
I'm guessing the difference is in the data-ember-action and the data-bindattr-*, but I don't know how to make it work. Anyone here knows why the click() event doesn't work and directly clicking does?
EDIT: If you have any questions about my question, feel free to ask.
EDIT2: I experimented a little more, and I can remove all HTML attributes from the button, and clicking on it will still work. I have no idea what is going on :(.
EDIT3: Okay, so it seems it only stops working when i remove the
Span within the button
Still no idea what is going on. (Yes, have also tried to fire the click event on the span)
EDIT4: As requested, here is all the code from my side. Note that I'm trying to click a button from twitch itself, of which ember side I do not own any code. This code is used by pasting it in the console on a twitch.tv stream and then starting it by calling initiateMessageProcessing. I'm sorry for the lot of hardcoded values, those are twitch' fields that I need. For now I'm just looking for a proof of concept.
var frequency = 5000;
var myInterval = 0;
var lastMessageId = 0;
function initiateMessageProcessing() {
if (myInterval > 0) {
clearInterval(myInterval);
}
myInterval = setInterval("checkMessages()", frequency);
}
function checkMessages() {
var chat = document.getElementsByClassName("chat-lines")[0];
processMessages(extractUnprocessedMessages(chat.children));
lastMessageId = parseInt(chat.lastElementChild.getAttribute("id").substring(5, 10));
}
function extractUnprocessedMessages(chat) {
var unprocessedMessages = [];
var chatId = 0;
for ( i = 0; i < chat.length; i++) {
chatId = parseInt(chat[i].getAttribute("id").substring(5, 10));
if (chatId > lastMessageId) {
unprocessedMessages.push(chat[i]);
}
}
return unprocessedMessages;
}
function processMessages(unprocessedMessages) {
var messageElement;
for ( i = 0; i < unprocessedMessages.length; i++) {
messageElement = unprocessedMessages[i].children[0].getElementsByClassName("message")[0];
if (messageElement != undefined && messageElement != null) {
if (messageElement.innerHTML.search("!test") !== -1) {
sendMessage('Hello world!');
}
}
}
}
function sendMessage(message) {
fillTextArea(message);
var button = $('.send-chat-button').get(0);
var event = new MouseEvent('click', {
bubbles : true
});
button.dispatchEvent(event);
}
function fillTextArea(message){
var textArea;
var chatInterface = document.getElementsByClassName("chat-interface")[0];
var textAreaContain = chatInterface.children[0];
textArea = textAreaContain.children[0].children[0];
textArea.value = message;
}
EDIT5: Eventlistener screenshot:
EDIT6: Edited source code to use $('.send-chat-button').click();
I have tried this, does not work in the current code, it does work if I manually fire this single command in the console when there is text in the chat. But sadly does not work in my code.
EDIT7: used Ember.run, still doesn't work.
EDIT8: used dispatchmouseevent, still doesn't work in context of code
It seems that the target site attaches event listeners without help of JQuery. If it is so, you cannot trigger it using jquery .click() method.
You can try directly mocking the browser event like this:
var button = $('.send-chat-button').get(0);
var event = new MouseEvent('click', {bubbles: true});
button.dispatchEvent(event);
This code will not work in IE8 and lower, but I guess it is not your case.
I know this post is quite old but I had been looking for an answer on this for a while and nothing really worked, after trying out A LOT of stuff I found it works when you focus the chatbox first then focus the button then triggering the click event!!! uuuhm yeah...
$('.chat_text_input').focus();
$('.send-chat-button').focus().trigger('click');
I have no idea why this works (and why it doesn't in any other way), but leaving any of the focusses out makes it fail or bug out.
Programmatically clicking a DOM element to make some action done is somewhat a wrong approach.
You should have define a method myAction() which will be called in two ways. First, from your ember action triggerMyAction() and second, after listening to a custom event, "myEvent".
Instead of $('.send-chat-button').click(); you will code $('something').trigger("myEvent") then.
Something like:
Em.Controller.extend({
myAction:function(){
//do your stuff
},
onMyEvent:function(){
$('something').on('myEvent',this.myAction);
}.on('didInsertElement'),
actions:{
triggerMyAction:function(){
this.myAction();
}
}
})
is there any one who is familiar with YUI jQuery frame work ?? i need very little help
please take the look at below code
It works perfect but the inputClick() is called when i press any button left or right but i dont want button, i want to call function when page loads means automatically
please help me some one.
in short I want to call inputclick(e){......} automatically when page load
i heard about domready function which is same like JQuery's document.ready function
so how should i call inputClick(e)??
please take look at this ::
<section id="btns">
<p>
<input type="button" value="Left">
<input type="button" value="Right">
</p>
</selection>
<script src="http://yui.yahooapis.com/3.5.1/build/yui/yui-min.js"></script>
<script>
document.querySelector('#btns').addEventListener("click", inputClick, false);
function inputClick(e){
var a = e.target.value;
window.alert(a); // displays Left or Right button value
}
</script>
i tried inputClick(Left); and inputClick(Roght); but do nothing :(
What i need is when page load ::
rnd = random(2);
switch(rnd)
case 1:
inputClick(Left);
case 2:
inputClick(Right);
i DONT want button or eventlistener
I hope this helps. http://jsfiddle.net/Rh7Ju/1/
Know that anything in the YUI().use() will execute when the DOM is ready.
YUI().use('node', 'event', function (Y) {
function inputClick(button_value) {
alert(button_value);
}
// called when the buttons are clicked
Y.one('#btns').on('click', function (e) {
inputClick(e.target.get('value'));
}, 'input');
inputClick('Right'); // called when the dom is ready.
});
After I looked at your question again, is seems like you are trying to randomly select a button and alert its value. So, maybe this is more what you're looking for?
http://jsfiddle.net/Rh7Ju/2/
Anyway, happy coding.
I have some form buttons
<input type="button" onclick="send_away('700302','update_item','0',2)" value="Change Quantity">
and they are calling the functions below: (different buttons call different functions from this script, which is embedded in the HTML file.
<script language="javascript" type="text/javascript">
function send_away(item_c,request_c,change_item_c,quantity_c){
form_c.item.value = item_c;
form_c.request.value = request_c;
form_c.change_item.value = change_item_c;
form_c.quantity.value = quantity_c;
form_c.submit();
}
//sends the form later
function later(){
address.incoming_address.value = 'l';
address.submit();
}
function address_now(){
form_c.incoming_address.value = 'n';
form_c.submit();
}
function remove_item(item_num){
form_c.removal.value = item_num;
form_c.submit();
}
</script>
The problem is, not one of these buttons works in firefox. They all work in every other browser I've tried.
Has anyone run into this kind of problem / know what I could be doing wrong? I've stared at it for a while and can't see anything, other than that my HTML doesn't validate very well, I don't have nearly time to fix all the validation problems though.
You can see the effect at http://www.terra-cotta-pendants.com/ - click a product and add it to cart - the buttons are on the cart page.
Thanks for any help.
add id="form_c" to your form and use document.getElementById('form_c') instead of just form_c
another option would be to access the form by using document.forms.form_c, but I have always preferred using id's