I am trying to modify a WordPress plugin which activates a game script when a button is pressed. I would like to be able to activate it with a combination of key presses instead (Shift + Control + F).
I have attempted wrapping the entire script in a keypress function, however, this did not work. I have confirmed that script is loaded via console log but pressing the key combination does not do anything.
Original code:
PHP
<?php
...
/* Insert the button*/
switch ($asteroids_buttonopt) {
case "push-1":
echo '<div><p style="text-align: center;">
<a href="#" onclick="'.$asteroids_start.'"><button>Click to Play Asteroids!!!</button>
</a></p></div>';
break;
...
}
?>
JS
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
function startAsteroids(color,address) {
var ver = getInternetExplorerVersion();
if(ver>=0){
color = typeof(color) != 'undefined' ? color : 'black';
document.onkeydown = function(ev) {
var key;
ev = ev || event;
key = ev.keyCode;
if(key == 37 || key == 38 || key == 39 || key == 40) {
//e.cancelBubble is supported by IE - this will kill the bubbling process.
ev.cancelBubble = true;
ev.returnValue = false;
}
}
var s =document.createElement('script');
s.type='text/javascript'
document.body.appendChild(s);
s.src = address;
void(0);
return false;
}
else{
color = typeof(color) != 'undefined' ? color : 'black';
var s =document.createElement('script');
s.type='text/javascript'
document.body.appendChild(s);
s.src = address;
void(0);
return false;
}
}
Any help would be greatly appreciated. The original plugin 'Asteroid Widget' was abandoned 8 years ago so I cannot seek help from the developers.
Instead of wrapping the entire page content, you should add the following onkeypress function to the end of the JS file.
Required Function
window.onkeypress=function(e){
if(e.ctrlKey && e.shiftKey && e.code==='KeyF' ){
startAsteroids('','/wp-content/plugins/asteroids-widget/gears/play-asteroids-yellow.min.js');
}
}
Complete resulting file
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
function startAsteroids(color,address) {
var ver = getInternetExplorerVersion();
if(ver>=0){
color = typeof(color) != 'undefined' ? color : 'black';
document.onkeydown = function(ev) {
var key;
ev = ev || event;
key = ev.keyCode;
if(key == 37 || key == 38 || key == 39 || key == 40) {
//e.cancelBubble is supported by IE - this will kill the bubbling process.
ev.cancelBubble = true;
ev.returnValue = false;
}
}
var s =document.createElement('script');
s.type='text/javascript'
document.body.appendChild(s);
s.src = address;
void(0);
return false;
}
else{
color = typeof(color) != 'undefined' ? color : 'black';
var s =document.createElement('script');
s.type='text/javascript'
document.body.appendChild(s);
s.src = address;
void(0);
return false;
}
}
window.onkeypress=function(e){
if(e.ctrlKey && e.shiftKey && e.code==='KeyF' ){
startAsteroids('','/wp-content/plugins/asteroids-widget/gears/play-asteroids-yellow.min.js');
}
}
Related
Please find the code below:
setTimeout(function() {
var objTextareaText = objTextArea.innerText;
var normalizedText = objTextareaText;
if (!countSpacesAsChars) {
normalizedText = objTextareaText.replace(/\s/g,"").replace(/ /g, "");}
strText = normalizedText.replace(/(\r\n|\n|\r)/gm, "").replace(/ /gi, " ");
//Strip Html tags
strText = normalizedText.replace(/(<([^>]+)>)/ig,"").replace(/^([\t\r\n]*)$/, "");
}, 50);
if (strText.length >= MaxLength) {
}
From the above if statement strText is returning as undefined.
Also if i include the if statement inside the settimeout function as below:
setTimeout(function() {
var objTextareaText = objTextArea.innerText;
var normalizedText = objTextareaText;
if (!countSpacesAsChars) {
normalizedText = objTextareaText.replace(/\s/g, "").replace(/ /g, "");
}
strText = normalizedText.replace(/(\r\n|\n|\r)/gm, "").replace(/ /gi, " ");
//Strip Html tags
strText = normalizedText.replace(/(<([^>]+)>)/ig,"").replace(/^([\t\r\n]*)$/, "");
if ((e.data.domEvent.$.keyCode === 8) || (e.data.domEvent.$.keyCode === 46) || ((e.data.domEvent.$.shiftKey)
&& (e.data.domEvent.$.keyCode === 36)) || ((e.data.domEvent.$.shiftKey) && (e.data.domEvent.$.keyCode === 35))
|| (e.data.domEvent.$.keyCode === 35) || (e.data.domEvent.$.keyCode === 36) || (e.data.domEvent.$.keyCode === 37)
|| (e.data.domEvent.$.keyCode === 38) || (e.data.domEvent.$.keyCode === 39) || (e.data.domEvent.$.keyCode === 40)) {
showCharacterCount();
e.cancelBubble = false;
e.returnValue = true;
return true;
}
// Reaches Max Length - Shows error MAX_VALUE Reached Error Msg.
if (strText.length >= MaxLength) {
showCharacterCount();
e.cancelBubble = true;
e.returnValue = false;
e.cancel();
e.stop();
return false;
} else {
showCharacterCount(strText);
e.cancelBubble = false;
e.returnValue = true;
return true;
}
}, 50);
By above way there is an issue with key events.
e.cancelBubble = true;
e.returnValue = false;
e.cancel();
e.stop();
return false;
These code will not work.
So please suggest a solution.
Please Note: Settimeout function should be used as i am getting the count of the characters from RTF in salesforce.
Use below code as there Closure added to setTimeout
setTimeout(function() {
var objTextareaText = objTextArea.innerText;
var normalizedText = objTextareaText;
if (!countSpacesAsChars) {
normalizedText = objTextareaText.replace(/\s/g,"").replace(/ /g, "");}
strText = normalizedText.replace(/(\r\n|\n|\r)/gm, "").replace(/ /gi, " ");
//Strip Html tags
strText = normalizedText.replace(/(<([^>]+)>)/ig,"").replace(/^([\t\r\n]*)$/, "");
//change below code line as closure
}(), 50);
// now strText is not undefined
if (strText.length >= MaxLength) {
}
If you want to use setTimeout variable value outside it , then can do using closure function , because it(a closure function) has access to outside , inside and within a function. more info at closure function
I have a script that tracks outgoing links when the link is inside an <a> tag.
The script is from here
The script will track html inside the tag or an image.
What I need is for it to track a button as seen below.
Here is the code I guess I need to modify:
function clicktracker(e)
{
var ie = navigator.appName == "Microsoft Internet Explorer";
var src = ie ? window.event.srcElement : e.target;
var tag = (src.tagName.toLowerCase() != "a") ? src.parentNode : src;
if (!tag || tag.tagName.toLowerCase() != "a") return;
domain = clicktracker_domain (tag.href);
extension = clicktracker_extension(tag.href);
if ( clicktracker_inarray(clicktracker_domains, domain) &&
!clicktracker_inarray(clicktracker_extensions, extension)) return;
var url = tag.href;
var title = '';
if (!title) if (tag.tagName.toLowerCase() == "a") title = clicktracker_innertxt(tag.innerHTML);
if (!title) if (tag.tagName.toLowerCase() == "a") title = clicktracker_innertxt(tag.title);
if (!title) if (src.tagName.toLowerCase() == "img") title = clicktracker_innertxt(src.alt);
if (!title) if (src.tagName.toLowerCase() == "img") title = clicktracker_innertxt("Image");
url = escape(url .substr(0, 150));
title = escape(title.substr(0, 150));
if (url && title) setTimeout("clicktracker_aux('"+url+"', '"+title+"')", 10);
return;
}
Here is the button I want to track
<button type="button" title="title" style="background:#cda85c;" class="button btn-cart" onclick="window.open('http://www.example.com')"><span><span><?php echo $this->__('Buy Now') ?></span></span></button>
Here is the full script:
function clicktracker_inarray (arr, val)
{
for (var i in arr) if (arr[i] == val) return true;
return false;
}
// ***** clicktracker_innertxt *****
function clicktracker_innertxt(str)
{
str = str.replace(/<[^>]*>/g, ' ');
str = str.replace( /&/g, '&');
str = str.replace( / /g, ' ');
str = str.replace( /^\s+/g, '');
str = str.replace( /\s+$/g, '');
return str;
}
// ***** URL *******************************************************************
var clicktracker_re_scheme = "^\\w+://";
var clicktracker_re_folder = "((?:-|\\w|\\.)*)";
var clicktracker_re_domain = clicktracker_re_scheme+ clicktracker_re_folder;
var clicktracker_re_urlall = clicktracker_re_domain+"(?:/"+clicktracker_re_folder+')*';
// ***** clicktracker_domain *****
function clicktracker_domain(url)
{
var reg = new RegExp(clicktracker_re_domain);
var match = reg.exec(url);
if (!match) return "";
match = match[match.length-1];
return match;
}
// ***** clicktracker_extension *****
function clicktracker_extension(url)
{
var reg = new RegExp(clicktracker_re_urlall);
var match = reg.exec(url);
if (!match) return "";
match = match[match.length-1].split(".");
return (match.length >= 2) ? match[match.length-1] : "";
}
// ***** Track *****************************************************************
// ***** clicktracker_aux *****
function clicktracker_aux(url, title)
{
var img = new Image();
img.src = clicktracker_url+"?url="+url+"&title="+title+"&rand="+Math.random();
}
// ***** clicktracker *****
function clicktracker(e)
{
var ie = navigator.appName == "Microsoft Internet Explorer";
var src = ie ? window.event.srcElement : e.target;
var tag = (src.tagName.toLowerCase() != "a") ? src.parentNode : src;
if (!tag || tag.tagName.toLowerCase() != "a") return;
domain = clicktracker_domain (tag.href);
extension = clicktracker_extension(tag.href);
if ( clicktracker_inarray(clicktracker_domains, domain) &&
!clicktracker_inarray(clicktracker_extensions, extension)) return;
var url = tag.href;
var title = '';
if (!title) if (tag.tagName.toLowerCase() == "a") title = clicktracker_innertxt(tag.innerHTML);
if (!title) if (tag.tagName.toLowerCase() == "a") title = clicktracker_innertxt(tag.title);
if (!title) if (src.tagName.toLowerCase() == "img") title = clicktracker_innertxt(src.alt);
if (!title) if (src.tagName.toLowerCase() == "img") title = clicktracker_innertxt("Image");
url = escape(url .substr(0, 150));
title = escape(title.substr(0, 150));
if (url && title) setTimeout("clicktracker_aux('"+url+"', '"+title+"')", 10);
return;
}
// ***** Attach Events *********************************************************
if (navigator.appName == "Microsoft Internet Explorer")
document.attachEvent ('onclick', clicktracker);
else document.addEventListener('click', clicktracker, false);
edit*****
The clicks are then stored in the database and called for from a php page.
There's a lot going on in those scripts and it's not clear what you mean by "track", so I'll just give a short version:
document.addEventListener('click',function(e){
var tag=e.target.tagName.toLowerCase();
switch(tag){
case "a":
//use e.target to track this link event
break;
case "img":
//use e.target to track this image event
break;
case "button":
//use e.target to track this button event
break;
}
});
This listens for clicks anywhere on the page, and you use e.target to inspect the click.
Edit:
e is just the name I gave to the event object, which is automatically passed into the function by the event listener. One of the properties that's always in this object is target which contains a bunch of info about the event. if you drop console.log(e) inside the function in the event listener above, you can pull it up in Chrome, hit control+shift+i, go to the javascript console, and explore what's in there.
So I have a live website here: http://www.trock.net/#/downloads
What I am trying to do is preselect the "select operating system" option based on the users OS.
The apps.js is located here:
http://www.trock.net/js/app.js.
The raw HTML for the download page is located here: www.trock.net/includes/downloads.html
Now, the issue is that the detectOS function I have does not seem to work. I have tried attaching it to ng-init on the app and ng-init on a div after the select box but that does not work. If I attach ng-click and click it, it works as expected.
Each option has an ID which is what I am using to find the element so I can set 'selected' to true. Is there a better way of doing this using angular?
How would I go about making this work, is the issue that I am calling the function too early or perhaps too late?
Code of interest in apps.js:
//Auto select Operating System based on detection
$scope.detectOS = function() {
var processorArchitecture = "";
var userOS = "";
if (navigator.userAgent.indexOf("WOW64") != -1 ||
navigator.userAgent.indexOf("Win64") != -1 ){
processorArchitecture = "64";
} else { //Assume 32 bit
processorArchitecture = "32";
}
//Detect the OS
if (navigator.platform.indexOf("Win") != -1){
userOS = "win";
if (processorArchitecture == "64")
processorArchitecture = "32";
}
else if (navigator.platform.indexOf("Mac") != -1){
userOS = "mac";
if (processorArchitecture == "64")
processorArchitecture = "32";
}
else if (navigator.platform.indexOf("Lin") != -1){
userOS = "lin";
}
//Check for valid detection
if (userOS != "" && processorArchitecture != "") {
//Valid match found
var optionSelectionID = userOS + processorArchitecture;
//Auto detect OS
//We will find only 1 instance of said query
angular.element( document.querySelector( "#win32") )[0].selected = true;
}
};
I also made a plunker which actually works so it must be something else I am doing on the website (perhaps loading in other .html pages ajax style).
Link: http://plnkr.co/edit/zlmk24aVHeBNz79PjypP?p=preview
Okay so I solved the issue, it seems that the presence of the ng-model was stopping the above code from working. Removing it means it worked fine but I needed the ng-model set to do other things.
Anyway, I ended up using the ng-options derivative like so to solve my problem:
<select ng-model="operatingSystemID" ng-options="os as os.label for os in osList track by os.id" id="download-dropdown">
I used this as my osList:
//Create supported operating systems list
$scope.osList = [
{
id: "win32",
label: "Windows (32/64 bit)"
},
{
id: "mac32",
label: "Mac OS (32/64 bit)"
},
{
id: "lin32",
label: "Linux (32 bit)"
},
{
id: "lin64",
label: "Linux (64 bit)"
}
];
And this was my new detectOS function:
$scope.detectOS = function() {
var processorArchitecture = "";
var processorArchitectureCompat = "";
var userOS = "";
var userOSNicename = "";
if (navigator.userAgent.indexOf("WOW64") != -1 ||
navigator.userAgent.indexOf("Win64") != -1 ){
processorArchitecture = "64";
} else { //Assume 32 bit
processorArchitecture = "32";
}
processorArchitectureCompat = processorArchitecture;
//Detect the OS
if (navigator.platform.indexOf("Win") != -1){
userOS = "win";
userOSNicename = "Windows";
if (processorArchitecture == "64")
processorArchitectureCompat = "32";
}
else if (navigator.platform.indexOf("Mac") != -1){
userOS = "mac";
userOSNicename = "Mac OS";
if (processorArchitecture == "64")
processorArchitectureCompat = "32";
}
else if (navigator.platform.indexOf("Lin") != -1){
userOS = "lin";
userOSNicename = "Linux";
}
//Check for valid detection
if (userOS != "" && processorArchitecture != "") {
//Valid match found
var optionSelectionID = userOS + processorArchitectureCompat;
//Output detected option to os message section
$scope.os_detection_box = $sce.trustAsHtml("(We have detected your OS as " + userOSNicename + " " +processorArchitecture + " bits)");
//Auto select the detected option
$scope.operatingSystemID = {id: optionSelectionID};
}
};
Hi there i have this script and im trying to make it work so that only a certain amount of numbers (8 numbers) are allowed in it. What do i have to add to this??
<SCRIPT TYPE="text/javascript">
function numbersonly(myfield, e, dec)
{
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
// control keys
if ((key==null) || (key==0) || (key==8) ||
(key==9) || (key==13) || (key==27) )
return true;
// numbers
else if ((("0123456789").indexOf(keychar) > -1))
return true;
// decimal point jump
else if (dec && (keychar == "."))
{
myfield.form.elements[dec].focus();
return false;
}
else
return false;
}
</SCRIPT>
You can either add the attribute size (size="8") to your field directly or do it using JS :
var sizeLimitation = document.createAttribute('size');
sizeLimitation.value = 8;
myfield.setAttributeNode(sizeLimitation);
in in Input field, if the user presses Backspace or Delete key, is there a way to get the deleted character.
I need to check it against a RegExp.
Assuming the input box has an id 'input'. Here is how with least amount of code you can find out the last character from the input box.
document.getElementById("input").onkeydown = function(evt) {
const t = evt.target;
if (evt.keyCode === 8) { // for backspace key
console.log(t.value[t.selectionStart - 1]);
} else if (evt.keyCode === 46) { // for delete key
console.log(t.value[t.selectionStart]);
}
};
<input id="input" />
The following will work in all major browsers for text <input> elements. It shouldn't be used for <textarea> elements because the getInputSelection function doesn't account for line breaks correctly in IE. See this answer for a (longer) function that will do this.
function getInputSelection(input) {
var start = 0, end = 0;
input.focus();
if ( typeof input.selectionStart == "number" &&
typeof input.selectionEnd == "number") {
start = input.selectionStart;
end = input.selectionEnd;
} else if (document.selection && document.selection.createRange) {
var range = document.selection.createRange();
if (range) {
var inputRange = input.createTextRange();
var workingRange = inputRange.duplicate();
var bookmark = range.getBookmark();
inputRange.moveToBookmark(bookmark);
workingRange.setEndPoint("EndToEnd", inputRange);
end = workingRange.text.length;
workingRange.setEndPoint("EndToStart", inputRange);
start = workingRange.text.length;
}
}
return {
start: start,
end: end,
length: end - start
};
}
document.getElementById("aTextBox").onkeydown = function(evt) {
evt = evt || window.event;
var keyCode = evt.keyCode;
var deleteKey = (keyCode == 46), backspaceKey = (keyCode == 8);
var sel, deletedText, val;
if (deleteKey || backspaceKey) {
val = this.value;
sel = getInputSelection(this);
if (sel.length) {
deletedText = val.slice(sel.start, sel.end);
} else {
deletedText = val.charAt(deleteKey ? sel.start : sel.start - 1);
}
alert("About to be deleted: " + deletedText);
}
};
No, there is no variable that stores the deleted char. Unless you have a history for Undo/Redo, but it would be difficult to get the information out of that component.
Easiest would be to compare the contents of the input field before and after delete/backspace have been pressed.
You could try something with the caret position:
function getCaretPosition(control){
var position = {};
if (control.selectionStart && control.selectionEnd){
position.start = control.selectionStart;
position.end = control.selectionEnd;
} else {
var range = document.selection.createRange();
position.start = (range.offsetLeft - 1) / 7;
position.end = position.start + (range.text.length);
}
position.length = position.end - position.start;
return position;
}
document.getElementById('test').onkeydown = function(e){
var selection = getCaretPosition(this);
var val = this.value;
if((e.keyCode==8 || e.keyCode==46) && selection.start!==selection.end){
alert(val.substr(selection.start, selection.length));
} else if(e.keyCode==8){
alert(val.substr(selection.start-1, 1));
} else if(e.keyCode==46){
alert(val.substr(selection.start, 1));
}
}
Tested on Chrome 6. See jsFiddle for an example