Adobe Animate CC, HTML5 Canvas.
I have a few buttons that I'm trying to set up dynamically - set the text on each one, set their colors, etc. One thing I can't seem to figure out is how to get these buttons to do stuff to themselves when moused-over or clicked.
In this block of code, I just want a button to change the text on itself when moused-over. What am I missing?
var frequency = 3;
stage.enableMouseOver(frequency);
function fl_MouseOverHandler(event) {
event.target.theTitle.text = "You moused-over me!"
}
for (a=0; a<11; a++) {
this.container["button"+a].theTitle.text = "Button Number "+ a;
this.container["button"+a].addEventListener("mouseover", fl_MouseOverHandler);
}
I don't know that the theTitle attribute is, and I guess this is wrong. Try:
event.target.textContent = 'You moused-over me!'
this refers in a listener to the object you're listening, so the button that has been hovered in this case. So you can just do this.innerText = 'whatever'
A js fiddle
Hope it helped
Matt
Related
Right now i have four images which are being dynamically presented on html. This is done via an onload function. Basically when i click on of those wheels I would like the image to change for around one second then go back. But right now only one wheel changes colour which is quite annoying.
function setWheels() {
document.querySelector(".blue-wheel").innerHTML = "<img src='blue-dark.svg.svg' onclick='buttonEvent()'>";
document.querySelector(".red-wheel").innerHTML = "<img src='red-dark.svg.svg' onclick='buttonEvent()'>";
document.querySelector(".green-wheel").innerHTML = "<img src='green-dark.svg.svg'>";
document.querySelector(".yellow-wheel").innerHTML = "<img src='yellow-dark.svg.svg'>";
}
function buttonEvent() {
if (document.querySelector(".blue-wheel")) {
document.querySelector(".blue-wheel").innerHTML = "<img src='blue-light.svg.svg'>";
setTimeout(setWheels, 800);
}
else if (document.querySelector(".red-wheel")) {
document.querySelector(".red-wheel").innerHTML =<img src='red-light.svg.svg'>";
setTimeout(setWheels, 800);
}
}
I havnt added the other coloured wheels as i do predict that they will have the same effect. I do believe that the setTimeout may be one of the problems as I'm calling the setWheels function but the first if statement seems to be the only one that changes colour even when i click the other div.
Your if statements aren't checking anything useful. if(document.querySelector(".blue-wheel")) is only checking if that element is there, not if the image inside was clicked.
If you want to know which image was clicked, pass it in as a parameter to the function.
<img src='blue-dark.svg.svg' onclick='buttonEvent(this)'>
and in your javascript, just change the src for the image that was clicked and then set a timeout to change it back.
function buttonEvent(e) {
e.src = e.src.replace('dark', 'light');
setTimeout(() => {e.src = e.src.replace('light', 'dark')}, 800);
}
if you want to protect against fast clicking while the image is already highlighted (improve performance) you can add a return:
function buttonEvent(e) {
if (!e.src.includes('dark')) return;
e.src = e.src.replace('dark', 'light');
setTimeout(() => {e.src = e.src.replace('light', 'dark')}, 800);
}
You are missing a "
.innerHTML =<img src='red-light.svg.svg'>";
should be
.innerHTML = "<img src='red-light.svg.svg'>";
you can use a variable (let x=0) to count on what image are you on. then make function that will see what x = 0 so it will show the first image then add one to the x (like "x++")but before you show the image you need to remove the last one, so then you need to loop through the images (you can give the same class to the images) like ".forEach()" and in that function you can see if that image is on the page or is shown to the user then just remove it, then x =1 in that case just show the second image and so on. you can add "if" statement that will check "if x>=(image count)" when that happens then just "x=0" and it will reset
I'm trying to make a text based idle game where multiple buttons are involved, and text around those.
Whenever I try to put text after the "Work" button it stops working, stops calling the callback on click.
I tried putting the text in a separate div, which didn't work, I also tried putting the button in its own div, which made things worse. The last thing I tried was putting the text written by the write functions (which made the formatting terrible) in a paragraph tag which somehow also didn't work.
I don't know what else to try. The only thing that doesn't seem to break it so far is putting other buttons after it.
I'm using a function to create buttons called createButton(), it takes in 3 arguments, the button text, the button ID, and the button callback, and to draw text I'm using a "custom" write function (details at bottom).
For the work button I'm passing in the work() function as the callback.
createButton function:
function createButton(text, id, callback){
// console.log(text + " " + id + " " + callback)
var button = document.createElement("button");
button.innerHTML = text; //create a button element
//var body = document.getElementsByTagName("body")[0];
gameDiv.appendChild(button); //set its parent to the game div
button.addEventListener ("click", callback); //add the callback as a listener
}
work function:
function work(){
money++;
//TODO: find better way of updating money counter
draw(); //redraw to update money counter
if(stage == 1){ //increment the current stage if needed (for pacing)
stage = 2;
setTimeout(function(){
buttonStage = 1;
createButton("Buy Box", "buyBox", buyBox);
}, 1000);
}
}
draw function:
function draw(){
clear(); //clear the screen
for(var i=0;i<stage;i++){
switch(i){
case 0:
writeln("Do this");
writeln(" |");
writeln(" |");
writeln("▼");
createButton("Work", "work", work); //recreating a button every second might be a problem, but i dont know how to get it to position properly otherwise
break;
case 1:
write("<div id=\"stage2\">");
writelnDiv("<br><br>Money: " + Math.round((money*100)/100), "stage2");
writelnDiv("", "stage2");
writelnDiv("Now do this", "stage2");
writelnDiv(" |", "stage2");
writelnDiv(" |", "stage2");
writelnDiv("▼", "stage2");
write("</div>")
if(buttonStage > 0){
createButton("Buy Box", "buyBox", buyBox);
}
break;
}
}
}
The write, writeDiv, writeln, and writelnDiv functions both just add the text to the div's innerHTML.
All code is here: https://js.do/Grimtin10/637778
The solution is probably simple, but I don't exactly know what I'm doing with javascript.
If any more info is needed to solve this I can provide it.
Alright, I figured out a solution.
Instead of using document.createElement I just created the button using HTML tags directly appending it to the div.
It's kind of an awful way of doing it, but it works.
I am creating a Chrome Extension similar to the "Search on Google" when you right click on a selected text. However, I need mine to also work when right clicking on a mailto: e-mail link. How can I select the innerHTML, to select the e-mail address, and pass this information onto the extension to be searched?
I managed to make it work with the selected text (when highlighting text on the website) and right-clicking, but not when right-clicking on a hyperlinked e-mail address.
for(var i=0; i<numentries; i++)
{
//alert(_all[i][3]);
if(_all[i][3])
{
_all[i][0] = chrome.contextMenus.create({"title": _all[i][1], "contexts":["selection", "link"], "onclick": searchOnClick});
//alert("Menuitem created");
}
else _all[i][0] = -1;
}
var ask_options = getItem("_askoptions")=="true"? true : false;
if(ask_options){
//show separator
chrome.contextMenus.create({"type": "separator", "contexts":["selection", "link"]});
//show the item for linking to extension options
chrome.contextMenus.create({"title": "Options", "contexts":["selection", "link"], "onclick": function(){chrome.tabs.create({"url":"options.html"});}});
}
}
function searchOnClick(info, tab)
{
var itemindex = 0;
for(var i=0; i<numentries; i++)
{
if(info.menuItemId == _all[i][0])
{
//alert(i);
itemindex = i;
}
}
var ask_fg = getItem("_askbg")=="true"? false : true;
var ask_next = getItem("_asknext")=="true"? true : false;
var index = 1000;
var targetURL = _all[itemindex][2].replace("TESTSEARCH", info.selectionText);
targetURL = targetURL.replace("%s", info.selectionText);
Right now, it's only searching for the selection. When I attempt to search for a e-mail address hyperlink, the searched word is "undefined".
I need to change "undefined" to the e-mail address in the hyperlink.
Here is what I need to happen: https://i.imgur.com/2qJrwmk.png
You need to add an event listener for the contextmenu.
Using the example cat gave, I created a quick jsfiddle:
https://jsfiddle.net/kds2Lze8/
The code below adds the event listener to the document and is triggered on right click. Using that event you can then get the source element and ultimately the innerHTML.
Hope it helps!
document.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
alert(ev.srcElement.innerHTML);
return false;
}, false);
I'm not sure about some of the Chrome-extension-specific stuff (and your snippet is giving an error that I had trouble debugging without your HTML markup), but I think this script will demonstrate how to do what you want.
Edit:
You did indeed say you wanted to know how to run the script in response to a right-click, but I omitted that part. Sorry about that. The revised version should clarify that. It logs the innerHTML of the clicked element (although not on left-clicks) if the element is an anchor whose href attribute starts with mailto:.
// Run the 'checkAnchorForEmail' function on non-primary click events
document.addEventListener("auxclick", checkAnchorForEmail);
function checkAnchorForEmail(event){ //'event' will be our local name for any event that triggers this function
// Refer to the event's target element as 'clickedElement'
let clickedElement = event.target;
// If the element was an anchor with an 'href' attribute...
if(clickedElement.tagName.toLowerCase() === "a" && clickedElement.href){
// Define a string to identify anchors with emails
let comparedString = "mailto:";
// Only respond if the href begins with that particular string
if(clickedElement.href.indexOf(comparedString) === 0){
// Now we know the user right-clicked* an `a` element with an email address and can act accordingly
console.log(clickedElement.innerHTML);
}
}
}
// *Note that the 'auxclick' event is triggered by any non-primary button click. To isolate right-clicks, the 'contextmenu' event may be useful.
test#google.com<br />
google docs<br />
test2#google.com
One other thing:
If you need to prevent the context menu from appearing until your script has completed its tasks, you can use event.preventDefault();, but then you would need to show the menu manually later. One way to do this is by firing the 'contextmenu' event on the target element.
It's possible that doing so would cause this script to run again, creating an infinite loop. If this happens, you might try calling the preventDefault method conditionally like this (untested):
function checkAnchorForEmail(event){
// The above code goes here...
// Now we know the user right-clicked* an `a` element with an email address and can act accordingly
if(event.target.dataset.ready != "true"){ // Check the data-ready attribute
// event.preventDefault();
// event.target.dataset.ready = "true" // Set the data-ready attribute
// Make your changes to the context menu here
}
else{
// The changes have already been made, so show the context menu here
// (maybe using a technique like the one in the link below)
}
}
Here is a suggestion for using the MouseEvent interface to open the context menu, as mentioned in the in-code comments.
In my current assignment I got:
Create a toggle button on the html page that visually indicates what state it is in by changing the text displayed on it (e.g. changes between “up” and “down”, or “smiling” and “not smiling”) and by switching between two images, as well.
a. Hint: you will have to use a “state” variable outside the button’s listener callback function to re- member the button’s state between event callbacks.
4. Use the toggle button to toggle the mouth between a smile and a frown. In your button ‘click’ listener, check the button’s state with an ‘if’ statement to control whether you are going to make a smile or a frown.
I am quite confused as I searched in web - there are so many ways to create a button, in Html or in css.
Can somebody post a similar example please ?
Use the element.click and provide a callback click function. In this case the callback is the update function.
In the update function, check for the current src, i.e. the source for the image element. Update the src of the image and the text of the button accordingly.
I have also made it interactable in the image part. If not required just remove this line
imageElem.click(update);
var imageElem = document.getElementById('test_Img'),
buttonElem = document.getElementById('test_Btn'),
img1 = 'http://www.fantazia.org.uk/images/600px-Smiley_svg_small.png',
img2 = 'http://www.clipartsgram.com/image/2060213170-sad-smiley-face-clipart-mclpbaqca.png';
imageElem.addEventListener("click", update);
buttonElem.addEventListener("click", update);
function update() {
var src, text;
if (imageElem.src === img1) {
src = img2;
text = 'Sad';
} else {
src = img1;
text = 'Smile';
}
buttonElem.value = text;
imageElem.src = src;
}
<input type = 'button' id="test_Btn" value = 'Smile'/>
<img id="test_Img" src='http://www.fantazia.org.uk/images/600px-Smiley_svg_small.png' />
I'm writing a vb.net program to automate and manage an online game. I'm using the Awesomium webcontrols to display and manipulate the pages of the game.
There is a point where I need to grab the data that's not shown in the source until the user hovers over a certain element, how can I use javascript (Not jquery please) to hover over it programatically until the data I need becomes available and then grabbed?
I apologise if this has been asked before (Which it has but from the perspective of someone who owns the web page) but I have been searching for hours for a solution and cant find anything.
What I've tried to use but failed is:
function findBpDate(){
document.getElementById('tileDetails').children[1].children[0].children[1].children[0].fireEvent('onmouseover');
return document.getElementsByClassName('text elementText')[0].textContent;
}
This returns "undefined" when it calls back to my application, I'm certain I'm pointing to the right DOM elements though.
This is what I want the javascript to "hover" on:
<span class="a arrow disabled">Send troops</span>
Once this element has been "hovered" on, this elements text changes to the text I need to grab:
<div class="text elementText">Beginners protection until 20/07/13 07:51 am.</div>
I've shown above what the element looks like when the mouse "hovers" on the element I need it to, however this changes a lot depending on which element the user hovers over while playing the game, from what i gather it's where the source keeps the text for each tooltip in the game.
So I need a function that will hover over a certain element and then while it's hovering, grab the text from the tooltip text/"text elementText" element.
Try WebView.InjectMouseMove(x, y).
Something like
public Point GetElementPosition(dynamic element)
{
dynamic rect = element.getBoundingClientRect();
using (rect)
{
return new Point(rect.left, rect.top);
}
}
dynamic element = webView.ExecuteJavascriptWithResult("document.getElementById('id')");
Point pos = GetElementPosition(element);
webView.InjectMouseMove(pos.X, pos.Y);
this is 10x easier with js/dom. http://jsfiddle.net/pA2Vd/
Do this...assuming you can get reference to elements somehow using by Id would have been lot easier.
var elm = document.getElementsByClassName('a arrow disabled')[0];
var txt = document.getElementsByClassName('text elementText')[0];
var evt = new Event('mouseover');
elm.dispatchEvent(evt);
var status = txt.innerText;
(helpfuL stuff down) otherwise you need to capture event, detect who fired it, check if that has this class and tag name. Lot of processing.
var txt,spn,status='';
document.getElementByTagName('span').forEach(function(d){
if (d.tagName=="div" && d.className == 'text elementText'){
var txt = d;
}
}
window.onmouseover = function(e) {
var elm = e.target;
if (elm.tagName=="SPAN" && elm.className == 'a arrow disabled') {
status=txt.innerText;
}
}