KineticJS circles won't respond to clicks - javascript

//Sets up endgame and text variables for later use
var final = '';
var message = '';
var endGame = false;
//Ends the game by disabling input
function endGame(){
feedButton.off('click');
hydrateButton.off('click');
sleepButton.off('click');
entertainButton.off('click');
startButton.off('click');
}
function gameStart(){
healthDrop();
sanityDrop();
patienceDrop();
difficult();
randOne();
randTwo();
randThree();
randFour();
function indicateBegin(){
imgk.setAttrs({fill: 'purple'});
}
function indicateOff(){
imgk.setAttrs({fill: false});
}
var timer = setTimeout(indicateOff, 4000);
}
//Should ready KineticJS buttons for use
startButton.on('click', gameStart);
feedButton.on('click', tamaHibachi.feed);
hydrateButton.on('click', tamaHibachi.hydrate);
sleepButton.on('click', tamaHibachi.sleep);
entertainButton.on('click', tamaHibachi.entertain);
So, I've been trying to create a game in KineticJS for a class project, but I've found that none of my buttons work. I don't know if the problem lies in this part of the code, but I would believe it does. Can anyone help?

Without more info on your code it's hard to say anything. For instance, all my objects have 'ID's... container is a DIV with an id of 'container' so that you can then do this:
container.addEventListener('mousedown', startListening, false );
I can't tell from your code if you have all that set up right. It's probably nothing with Kinetic, because I have a huge project on the go with Kinetic and all the event listeners are working just fine.

Related

javascript: remove/add class function

i found a very simple javascript function for a slideshow (here).
It works perfectly, but i want to change something about the control buttons. Right now, the play/pause button displays it's own name, like this:
<button class="controls" id="pause">Pause</button>
The javascript is set to run a function called pauseSlideshow under certain circumstances which not only pauses/resumes the slideshow, but also changes the displayed content of the button from "pause" to "play":
var playing = true;
var pauseButton = document.getElementById('pause');
function pauseSlideshow() {
pauseButton.innerHTML = 'Play';
playing = false;
clearInterval(slideInterval);
}
now, what i want to do is to leave the button empty and work width background images, and to do that i planned to do a simple class swap whenever the pauseSlideshow function is triggered. So, first i added a class called pause to the button with the desired background image set in the style:
<button class="controls pause" id="pause"></button>
and next i was going to do something like this:
var playing = true;
var pauseButton = document.getElementById('pause');
function pauseSlideshow() {
pauseButton.removeClass('pause');
pauseButton.addClass('play');
playing = false;
clearInterval(slideInterval);
}
(where play is another class with a different background image). Sufficient to say, as soon as pauseSlideshow runs, the function crashes. I'm writing something wrong or in the wrong place, but i know that the approach is viable.
please, can anybody point out the error?
EDIT:
Use $(pauseButton).removeClass('pause'); and
$(pauseButton).addClass('play');. addClass and removeCalss are jQuery
methods. And you need to add jQuery reference too. – user3698428
document.getElementById("pause") does not return a jQuery element.
.removeClass() and .addClass() are jQuery functions. So basically you
are trying to call jQuery functions on a non-jQuery element and it's
throwing an error. Change it to var pauseButton = $("#pause"); or
$(pauseButton).removeClass(...); $(pauseButton).addClass(...);
when i try either way, console returns: Uncaught ReferenceError: $ is not defined
When working in pure javascript, you should use this to add or remove class:
pauseButton.classList.remove('pause');
pauseButton.classList.add('play');
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

Why does jQuery.remove() remove mousedown listener from other div element?

I'm working on a HTML5 friendly drag and drop system and I've encountered another mystery that seems to make no sense...
The system is working in Edge - it's when I'm emulating IE8 that I encounter this latest problem.
I have a set of '.draggable' divs that get the following listener attached:
$(document).ready(function() {
$('#reset-button').click(resetDraggables);
if (!dragAndDropSupported()) {
var $draggables = $('.draggable');
$draggables.each( function (index) {
$(this).mousedown( jQueryStartDrag );
});
}
}
The draggables can be sent back to their original locations by hitting a 'reset' button. That all works fine.
The problem is - any divs that get sent back to their origins are no longer draggable. Even if I re-attach the listener in the reset function, it does not fire. Once again, this issue is only happening when I'm emulating IE8 and I don't remove the listener anywhere in my code.
function resetDraggables() {
if ( !$('#reset-button').hasClass('inactive') ) {
var $dropTargets = $('.drop-target');
$dropTargets.each(function (index) {
var draggableId = $(this).attr('data-contains');
var $originDraggable = $('#' + draggableId);
if ($originDraggable.attr('id')!=undefined) {
var $droppedDraggable = $(this).find('.draggable');
$droppedDraggable.remove();
$originDraggable.removeClass('inactive').addClass('draggable').attr('draggable', 'true').css('filter', 'alpha(opacity=100)').hide().fadeIn('fast');
$('#' + draggableId).mousedown( jQueryStartDrag );
$(this).removeClass('occupied').attr('data-contains', '');
$('#reset-button').addClass('inactive');
}
});
}
}
I've realised it's the $droppedDraggable.remove() line that's causing the problem. I'm not sure why a line to remove ONE object would remove the listener from another. The $droppedDraggable object was cloned from the other; Is that causing the issue?
Any ideas what might be going on?
OK, so I replaced the jQuery remove() lines with...
var droppedDraggable = document.getElementById('dropped-' + draggableId);
droppedDraggable.outerHTML = "";
...and that has done the trick. I'm guessing there must have been some hidden association made between the objects when one was cloned from the other and remove()ing one removed the mousedown listener from the other.
If anyone has a better theory, feel free to let me know, but this seems to have solved the problem.
Edit
I've just realised the above fixed the problem in IE8, but not in 9. Great! If anyone has any pointers on how NOT to include a bunch of browser-specific work arounds in my code, I'd be very keen to hear them. Thanks.

Firing a manual click event on an button in ember.js doesn't give the required result

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();
}
}
})

how to repaint all the UI componenets in Jquery

I have a several divs connected to one another using the endpoint connections to one another. As I do a zoom in or zoom out, I need to repaint all the UI components. The UI components are drawn using the jsPlumb library(jquery/javascript based). There is a method in jsplumb which forces the repaint but it is not working as the way I want it to do. Here it is what I am trying to do.
$("div#explanation .plus").click(function(){
jsPlumb.repaintEverything();
var strongFont = parseFloat($("div.window strong").css('font-size'));
var newStrongFont = strongFont + 2;
$("div.window ").animate({
'height':'+=20px', 'width':'+=20px'
},"medium");
$("div.window strong").animate({
fontSize:newStrongFont
},"medium");
//This is not working
jsPlumb.repaintEverything();
jsPlumb.repaintEverything();
//I am calling here another function to repaint the div windows one by one
repaintWindows();
});
var repaintWindows = function(){
var jjl;
for(jjl=1;jjl<=xmlLength;jjl++)
{
var windo = "window"+jjl;
//alert("Window is ::"+windo);
jsPlumb.repaint(windo);
alert("Window is ::"+windo);
//_addEndpoints(wind, ["LeftMiddle", "BottomCenter"], ["TopCenter", "RightMiddle"]);
}
alert("the value of jjl is ::"+jjl+" \nThe value of xmlLength is::"+xmlLength);
};
The problem here is if I remove the
//alert("Window is ::"+windo);
from the repaintWindows method for loop, the windows get repainted during the next cycle of call. I want the repaint to work at the same time. If I keep the alert, then it does repaint the window at the same time. As well, at the end I dont want any kind of alert over there.
Can somebody please tell me where am I going wrong.
Any help is appreciated.
Thanks!
not sure, but try this one
$(window).resize(function() {
jsPlumb.repaintEverything();
});

How can I add a page indicator to this jquery div carosel I made?

I put together this quick carousel that I'm using to cycle through different divs that contain graphs and other various data. I would like to have something indicating which "page" or div you are currently viewing.
Here is an example of what I'm currently doing to iterate through the divs.
http://jsfiddle.net/d6nZP/64/
My plan is to have a row of dots that have either a active or none active state depending on which page is indicated in the row. But even a basic page counter would work at this point.
Any help would be greatly appreciated, Thanks!
here is a simple pager for your carousel, enjoy it ;)
http://jsfiddle.net/d6nZP/65/
Created something you can use http://jsfiddle.net/BadBoyBill/8yHmy/
$("div[id^=marquee]:gt(0)").hide();
function startTimer(){
i = setInterval(rotate, 2000);
return i;
}
var intID = startTimer();
function stopTimer(){
clearInterval(intID);
}
function rotate(){
reference = $("div[id^=marquee]:visible").hide().next("div[id^=marquee]");
reference.length ? $(reference).fadeIn() : $("div[id^=marquee]:first").fadeIn() ;
dot = $(".indicator-on[id^=indicator]").removeClass("indicator-on").next("a[id^=indicator]").addClass("indicator-on");
dot.length ? $(dot).addClass("indicator-on") : $("a[id^=indicator]:first").addClass("indicator-on");
}
$("div[id^=marquee]").each(function(){
$("#indicators").append("<a href='#' id='indicator' class='indicator'></a>");
$(".indicator:first").addClass("indicator-on");
});
$("a[id^=indicator]").click(function(e){
var index = $("a[id^=indicator]").index(this);
//alert(index);
$("div[id=marquee]").hide();
$("div[id=marquee]").eq(index).show();
$("a[id=indicator]").removeClass("indicator-on");
$("a[id=indicator]").eq(index).addClass("indicator-on");
stopTimer();
intID = startTimer();
e.preventDefault();
});
$("a[id=indicator], div[id=marquee]").mouseenter(function(){
stopTimer();
//alert("mouseenter");
}).mouseleave(function(){
stopTimer();
intID = startTimer();
//alert("mouseexit");
});
The easiest way to do this would be to put something in the content divs themselves that acts as a counter, i.e. in the first div put "1/3", in the next "2/3", etc. That method, of course, would have the disadvantage of not being very responsive to change. A better option is to keep a separate variable that keeps track of which element is visible, then when the "next" button is clicked, the variable is incremented, then a check is run to see if that index exists. If not, you loop back the beginning. The opposite, of course, with the previous button.

Categories