Fix play function - javascript

I am try to develope a Macro Recorder in html and javascript , my all functions seems to work correct , but wen i press play button its not work also i have try debug and there is no errors , i cant find any error or some thing wrong , how can i fix this bug.
Here is my current code
<!DOCTYPE html>
<html>
<head>
<title>Macro Recorder</title>
</head>
<body>
<button id="start">Start Recording</button>
<button id="stop">Stop Recording</button>
<button id="play">Play Recording</button>
<button id="save">Save Recording</button>
<button id="load">Load Recording</button>
<script>
var events = [];
var isRecording = false;
document.getElementById("start").addEventListener("click", function() {
isRecording = true;
events = [];
});
document.getElementById("stop").addEventListener("click", function() {
isRecording = false;
});
document.addEventListener("keypress", function(event) {
if (isRecording) {
events.push({
key: event.key,
charCode: event.charCode
});
}
});
document.getElementById("play").addEventListener("click", function() {
events.forEach(function(event) {
setTimeout(function() {
var event = new KeyboardEvent("keypress", {
key: event.key,
charCode: event.charCode
});
document.dispatchEvent(event);
}, 500);
});
});
document.getElementById("save").addEventListener("click", function() {
var data = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(events));
var downloadAnchorNode = document.createElement("a");
downloadAnchorNode.setAttribute("href", data);
downloadAnchorNode.setAttribute("download", "events.json");
document.body.appendChild(downloadAnchorNode);
downloadAnchorNode.click();
downloadAnchorNode.remove();
});
document.getElementById("load").addEventListener("click", function() {
var input = document.createElement("input");
input.setAttribute("type", "file");
input.addEventListener("change", function() {
var reader = new FileReader();
reader.onload = function() {
events = JSON.parse(reader.result);
};
reader.readAsText(input.files[0]);
});
input.click();
});
</script>
</body>
</html>
I am try to develope a Macro Recorder in html and javascript , my all functions seems to work correct , but wen i press play button its not work also i have try debug and there is no errors , i cant find any error or some thing wrong , how can i fix this bug.

In the keypress event (which is deprecated, please don't use it) you store the key property of the event, but then in the play function you expect the code property to be present, so that's why it doesn't work.
You should learn to use the debugger, you would have found the problem immediately.

Related

Javascript - use callback with addEventListener for "remove all" button

I'm adding a "remove all" button to my chrome extension which as the name suggests should serve to remove all saved links.
The button works only after I have performed some other action first (adding a link, removing a link etc) but of course, I want it to work right away.
I have read that this may be due to the code being asynchronous so I tried introducing a callback function with the help of this question: Add callback to .addEventListener however, it's still performing the same way it did before so maybe that wasn't the issue after all, or I may have read the other question wrong. I appreciate any tips so thank you in advance. I will try to figure it out myself in the meantime.
var urlList = [];
var i = 0;
document.addEventListener('DOMContentLoaded', function() {
getUrlListAndRestoreInDom();
// event listener for the button inside popup window
document.getElementById('save').addEventListener('click', addLink);
});
function addLink() {
var url = document.getElementById("saveLink").value;
addUrlToListAndSave(url);
addUrlToDom(url);
}
function getUrlListAndRestoreInDom() {
chrome.storage.local.get({
urlList: []
}, function(data) {
urlList = data.urlList;
urlList.forEach(function(url) {
addUrlToDom(url);
});
});
}
function addUrlToDom(url) {
// change the text message
document.getElementById("saved-pages").innerHTML = "<h2>Saved pages</h2>";
var newEntry = document.createElement('li');
var newLink = document.createElement('a');
var removeButton = document.createElement('button');
removeButton.textContent = "Remove";
removeButton.type = "button";
removeButton.className = "remove";
removeButton.addEventListener("click", function() {
var anchor = this.previousElementSibling;
var url = anchor.getAttribute("href");
removeUrlAndSave(url);
this.parentNode.remove();
});
newLink.textContent = url;
newLink.setAttribute('href', url);
newLink.setAttribute('target', '_blank');
newEntry.appendChild(newLink);
newEntry.appendChild(removeButton);
newEntry.className = "listItem";
document.getElementById("list").appendChild(newEntry);
}
function removeUrlAndSave(url) {
var index = urlList.indexOf(url);
if (index != -1) {
urlList.splice(index, 1);
saveUrlList();
}
}
function addUrlToListAndSave(url) {
urlList.push(url);
saveUrlList();
//}
}
function saveUrlList(callback) {
chrome.storage.local.set({
urlList
// }, function() {
// if (typeof callback === 'function') {
// //If there was no callback provided, don't try to call it.
// callback();
// }
// });
});
function removeMe(i) {
var fullList = documents.getElementsByClassName('listItem');
listItem[i].parentNode.removeChild(listItem[i]);
}
function removeAll() {
var removeList = document.getElementsByClassName("listItem");
while (removeList[0]) {
removeList[0].parentNode.removeChild(removeList[0]);
};
}
function registerElement(callback) {
var element = document.getElementById("remove-all-button");
element.addEventListener("click", callback);
}
registerElement(removeAll);
#list {
min-height: 360px;
max-height: 360px;
width: 300px;
margin: auto;
overflow: scroll;
}
<head>
<script type="text/javascript" src="popup.js"></script>
<link rel="stylesheet" href="popup.css">
</head>
<body>
<div>
<span id="hot-button">Hot Drops</span>
<li id="removeAll">
<button id="remove-all-button"> Remove All</button>
</li>
<span id="saved-pages"></span>
<div>
<ul id="list"></ul>
</div>
</div>
<input type="button" id="save" value="Add">
<input type="text" id="saveLink" name="member" value=""><br/>
<span id="settings-button">Settings</span>
</body>
</html>
there you go
jsfiddle
had to write this line to post link
http://jsfiddle.net/1w69bo8k/ - you made a lot of mistakes, where you put certain code, to using variables I never saw them defined anywhere in code
(you keep editing the question, I went from this fiddle you provided)
change back to your getUrlListAndRestoreInDom function, deleted the storage code
you update the storage and the urlList manually, rather do it after the update of local is successful

Clicking multiple time on Button, Multiple audio play (Older sounds overlap new) in JavaScript

When I click on button, audio start. But when I click the button multiple times, multiple audio playing simultaneously.
HTML CODE
<button id = 'bt'> Click Me </button>
JavaScript Code
<script type="text/javascript">
url = 'song.mp3';
var btn =document.getElementById('bt');
btn.addEventListener('click', function(){
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', url);
playFunc(my, 3);
});
function PlayFunc(target, RepeatCount) {
var soundFunc = function(){
RepeatCount--;
target.currentTime = 0;
if (RepeatCount>0)
target.play();
else
target.removeEventListener('ended', soundFunc);
}
target.addEventListener('ended', soundFunc)
target.play();
}
</script>
What I'm thinking as solution-
Before creating new click event, destroy last event fist then create new one.
When user click second, it check if cureentTime == 0, then play audio else start again or nothing happen.
Thanks to Gurpreet, your solution work.
On each click I'm creating a new audio element thats why multiple audio are playing.
Simply I saved my audio to a variable and passed to playFunc.
url = 'song.mp3'
const myAudio = new Audio(url);
var btn =document.getElementById('bt');
btn.addEventListener('click', function(){
playFunc(myAudio, 3);
});
function PlayFunc(target, RepeatCount) {
var soundFunc = function(){
RepeatCount--;
target.currentTime = 0;
if (RepeatCount>0)
target.play();
else
target.removeEventListener('ended', soundFunc);
}
target.addEventListener('ended', soundFunc)
target.play();
}
Just de-register the click event handler in the click event handler. In order to do this, you'll need a named function.
btn.addEventListener('click', doPlay);
function doPlay(){
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', url);
playFunc(audioElement, 3);
btn.removeEventListener('click', doPlay); // <-- de-register the handler
}
You can disable the button until the audio clip is over.
const url = 'http://www.noiseaddicts.com/samples_1w72b820/4927.mp3';
const my = new Audio(url);
var btn =document.getElementById('bt');
btn.addEventListener('click', function(){
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', url);
playFunc(audioElement, 3);
});
function playFunc(target, RepeatCount) {
btn.disabled=true;
var soundFunc = function(){
RepeatCount--;
target.currentTime = 0;
if (RepeatCount>0)
target.play();
else{
target.removeEventListener('ended', soundFunc);
btn.disabled=false;
}
}
target.addEventListener('ended', soundFunc)
target.play();
}

Unittesting in Karma : Keypress inside a text Input

Have a simple html text input:
<html>
<body>
<input id="inputstring" type="text" onkeypress="testcharacter" onKeyUp="testcharacter ">
<div id ="result"></div>
<script type="text/javascript" src="javascriptfile.js"></script>
<script>testcharacter .init();</script>
</body>
</html>
Would like to be able to run a unittest on each keypress that occurs inside this text input and check it against a particular key. Javascript file is:
'use strict';
window.testcharacter = window.testcharacter || {};
(function() {
var testcharacter = function(k){
var s = document.getElementById('inputstring').value
if(s!=null||s.trim()!=""){
if(k==65){
document.getElementById('result').innerHTML = 'You pressed A'
}
if(s.length==0)
{ document.getElementById('result').innerHTML = ''}
}
}
window.testcharacter.init = function(){
document.getElementById('inputstring').addEventListener('keyup', testcharacter );
document.getElementById('inputstring').addEventListener('keypress', testcharacter );
};
})();
A portion of my test file, concerning this portion I've got:
it('should display character count with each keypress', function(){
var triggerKeyDown = function(element,keycode){
var e = jQuery.Event("testcharacter");
e.which = keycode;
$(element).trigger(e)
var ee = jQuery.Event("keyup")
ee.which = keycode + 1;
$(element).trigger(ee)
r = document.getElementById('inputstring').value
expect(document.getElementById('result').innerHTML).toBe(expected);
expect(document.getElementById('inputstring').innerHTML).toBe(expected);
};
triggerKeyDown('inputstring','65')
});
Right now, the keypress and keyup don't seem to persist to the inputbox,(I can easily set the value using:
document.getElementById('inputstring').value = 'A' which passes other portions of the tests, but not the keypresses) although I can see that the events are firing:
Testing of values:
ALERT: <input id="inputstring" type="text"> // captured 'inputstring'
ALERT: '' // captured value of 'inputstring'.value and 'result'.innerHTML
ALERT: 65 // e.which value
ALERT: {type: 'keypress', timeStamp: 1474058737895, jQuery31006431827041498093: true, which: 65} // event created
Not sure how to:
(1) fire off keypress/keyup events in Jasmine
(2) apply those events to the specific html element.value
So I can test those values. I would like each keypress/keyup to be tested.
I found somthing that you can try, replace element\eventName with your elements and events(keypress/keyup):-
var jasmineExtensions = {
jQuerySpies: {},
spyOnEvent: function(element, eventName) {
var control = {
triggered: false
};
element.bind(eventName, function() {
control.triggered = true;
});
jasmineExtensions.jQuerySpies[element[eventName]] = control;
};
};
var spyOnEvent = jasmineExtensions.spyOnEvent;
beforeEach(function() {
this.addMatchers({
toHaveBeenTriggered: function() {
var control = jasmineExtensions.jQuerySpies[this.actual];
return control.triggered;
}
});
});
may be can this help you.
I think you should use Jquery Simulate module
jQuery.simulate() - Simulate events to help unit test user interactions.

HTML5 and File API in Chrome problem

I'm trying to get this piece of code work in Chrome (latest build 10.0.648.205) and it works as expected in Firefox. Here, the e.target.result of the showImage function is empty. Can anyone tell me what Am I doing wrong?
$(function () {
var dropbox = document.getElementById("dropimage");
dropbox.addEventListener("dragenter", function (e) {
this.className = "over";
e.preventDefault();
e.stopPropagation();
}, false);
dropbox.addEventListener("dragover", function (e) {
e.preventDefault();
e.stopPropagation();
}, false);
dropbox.addEventListener("dragleave", function (e) {
var target = e.target;
if (e && e === dropbox) {
this.className = "";
}
e.preventDefault();
e.stopPropagation();
}, false);
dropbox.addEventListener("drop", function (e) {
e.stopPropagation();
e.preventDefault();
var files = e.dataTransfer.files;
var count = files.length;
if (count > 0) {
handleFiles(files)
}
}, false);
function handleFiles(files) {
$("#droplabel").html("Processing...");
file = files[0];
var reader = new FileReader();
reader.onloadend = showImage;
reader.readAsDataURL(file);
}
function showImage(e) {
$("#playerImage").attr("src", e.target.result);
$("#droplabel").html("Done");
}
});
HTML is straight-forward (I took the lines that include the scripts for simplicity):
<html>
<body>
<img id="playerImage"/>
<div id="dropimage">
<span id="droplabel">Drop file here...</span>
</div>
</body>
</html>
Also, if I try to change the dropbox.addEventListener for jQuery's $.bind, it doesn't do anything at all. Any thoughts?
The problem was that I was opening the html as a file. Chrome doesn't like that, so I resolved the problem by placing my html file in the wwwroot folder and opening it using a localhost/dnd.html address.

Javascript onbeforedeactivate event

Internet Explorer only.
<input type="button" id="but" value="button2"/>
<textarea id="text" cols="40" rows="20"></textarea>
window.onload = function() {
var el = document.getElementById("text");
var but = document.getElementById("but");
el.onbeforedeactivate = function() { alert('out') };
but.onclick = function() { alert('click') };
}
When I click the button within the textarea (focus is on textarea), I expect both functions to trigger but its not happening.
Why?
Online Example
alert causes all sorts of trouble, esp. on IE but frankly on other browsers as well. I would avoid it.
Your example works fine if you don't use alert, but instead use another way of showing the events have been received:
window.onload = function() {
var el = document.getElementById("text");
var but = document.getElementById("but");
el.onbeforedeactivate = function() { display('out') };
but.onclick = function() { display('click') };
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
}
Updated fiddle
Tested on IE6, 7, and 8. With your original, I get the same result as you (just the "out" alert). With the update, I see both events do in fact occur.

Categories

Resources