respond to key press javascript - javascript

I'm sorry if this is basic, but I've searched and found nothing that works.
I want to load a web page. When that page loads, it displays an image. I want to have the page automatically start listening for a right arrow key press. When that happens, a function in my script will change the image (that part I have gotten to work by using a button that reacts when clicked).
It's the listening for and reacting to a key press I cannot get to work. Note that I'm using Safari, but I would like if possible for it to work in firefox or IE as well.
Please help thanks.
UPDATE TO RESPOND TO COMMENT: Here is what I tried, though I simplified the other part to make this shorter -- now it just writes a result to a div:
<html>
<head>
<script language="Javascript">
function reactKey(evt) {
if(evt.keyCode==40) {
document.getElementById('output').innerHTML='it worked';
}
}
</script>
</head>
<body onLoad="document.onkeypress = reactKey();">
<div id="output"></div>
</body>
</html>

If you are using jquery, you can do this:
$(document).keydown(function(e){
if (e.keyCode == 39) {
alert( "right arrow pressed" );
return false;
}
});

document.onkeydown= function(key){ reactKey(key); }
function reactKey(evt) {
if(evt.keyCode== 40) {
alert('worked');
}
}
http://jsfiddle.net/dY9bT/1/

Easiest thing to do is use one of the many many many hotkey libraries, like https://github.com/jeresig/jquery.hotkeys or https://github.com/marquete/kibo.
EDIT: try something like this (after you've already loaded Kibo's javascript).
In your body statement, add the onload handler: <body onload="setuphandler">.
Then add something like this (taken from the Kibo page):
<script type="text/javascript">
var k = new Kibo();
function setuphandler()
{
k.down(['up', 'down'], function() {
alert("Keypress");
console.log('up or down arrow key pressed');
});
}
</script>

Related

Disable right-button in Vue [duplicate]

I have a document content displayed on IFrame in MVC web application. The content should not be copied and printed . I tried to disable right click using two functions style="pointer-events:none;" oncontextmenu="return false" for Iframe, which is working fine.
But on right click, the pop up with 'View Frame Source', 'View Source' are displaying. How can I restrict this.!
Also, how to restrict the print screen option. I know there are other utilities from where anybody can capture data. But the client wants to restrict the print screen option.
<script lang=JavaScript>
function clickIE() {
if (document.all) {
return false;
}
}
function clickNS(e) {
if (document.layers || (document.getElementById && !document.all)) {
if (e.which == 2 || e.which == 3) {
return false;
}
}
}
if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown = clickNS;`enter code here`
}
else {
document.onmouseup = clickNS;
document.oncontextmenu = clickIE;
}
document.oncontextmenu = new Function("return false")
<body oncontextmenu="return false" onkeydown="if ((arguments[0] || window.event).ctrlKey) return false" >
<div id="div1" style="background-color:Red; height:120px">
<iframe id="id1" src="" name="I1" scrolling="no" height="100%" width="100%" marginwidth ="0" marginheight="0" onload="disableContextMenu();" style="pointer-events:none;" />
</div>
Please Any help appreciated.. !!
In order to disable the right click menu you could use the following snippet:
document.oncontextmenu = function() {
return false;
};
I made a JSFiddle that displays the effect.
Your question is a little confusing as the title is about right clicking, yet the bddy of the question is about copying and pasting and about using the print screen button. Whilst you can do some things with the right click button (already answered by other posts and well documented) generally your question is how to prevent people accessing the code/content or taking a print out of your content.
This isn't possible. Whilst you can make it more tricky for some users, it will never succeed against those who are determined enough.
First of, even if you (somehow) disabled the print screen button on the keyboard, there are many screen capture programs out there... And I can't see how it will (ever) be possible to detect another program doing this from within the limitations of website code.
Any javascript solution can fail, they can turn off javascript.
Even if you managed to prevent some one from viewing the source code and copying the HTML, some one could just scrape the content direct from the site.
I have a friend who is a graphic designer and he wanted to do this (disable people copying images in this case). I told him not to bother, if they want to take the content you put into the public domain, they will. A water mark may help but only in some situations. Personally, I'd give up on this task and just accept it, and focus on more interesting tasks.
This worked for me fine:
window.frames["your_iframe_id"].contentDocument.oncontextmenu = function(){
return false;
};
We can't just disable right click on the iframe. Because of the iframe content is loading from another source so our code will not work on it. Here I found a solution which is the only option we have.
<html>
<head>
<title>Disable Context Menu</title>
<script type="text/jscript">
function disableContextMenu()
{
window.frames["fraDisabled"].document.oncontextmenu = function(){alert("No way!"); return false;};
// Or use this
// document.getElementById("fraDisabled").contentWindow.document.oncontextmenu = function(){alert("No way!"); return false;};;
}
</script>
</head>
<body bgcolor="#FFFFFF" onload="disableContextMenu();" oncontextmenu="return false">
<iframe id="fraDisabled" width="528" height="473" src="local_file.html"></iframe>
<div style="width:528px;height:473px;background-color:transparent;position:absolute;top:0px;">
</body>
</html>
1.) Disabling a right-click in iFrame using jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
// Function to block the right click in the iFrame
<script type="text/jscript">
function injectJS(){
var frame = $('iframe');
var contents = frame.contents();
var body = contents.find('body').attr("oncontextmenu", "return false");
var body = contents.find('body').append('<div>New Div</div>');
}
</script>
Call the "injectJS()" function in the iFrame
<iframe id="myiframe" width="528" height="473" onload="injectJS()"></iframe>
2.) Disable the right-click in the webpage
With javascript alone
document.addEventListener('contextmenu', event => event.preventDefault());
Here's an example in jQuery (Note: pressing the right mouse button will fire three events: the mousedown event, the contextmenu event, and the mouseup event)
// With jQuery
$(document).on({
"contextmenu": function(e) {
console.log("ctx menu button:", e.which);
// Stop the context menu
e.preventDefault();
},
"mousedown": function(e) {
console.log("normal mouse down:", e.which);
},
"mouseup": function(e) {
console.log("normal mouse up:", e.which);
}
});
If you have any questions leave a comment below.
window.frames["your_iframe_id"].document.oncontextmenu = function(){ return false; };

Qualtrics: Pressing enter key to emulate continue button

I'm very new to JavaScript, and I'm currently trying to add a custom code to my Qualtrics survey that makes it so pressing the enter key continues the survey. I have a code that should be working; however, I'm getting an "Unexpected token )" error.
Here is the code:
Qualtrics.SurveyEngine.addOnload(function()
{
document.addEventListener("keydown", function(e) {
if (e.keyCode === 13) {
function(){
that.clickNextButton();
}
}
}
});
the "clickNextButton" function was found in the Qualtrics API document and is supposed to emulate the next button click. The function is clickNextButton(), but the example provided has the code as that.clickNextButton().
The example they use is below:
//Hides the next button and displays the question
//for 5 seconds before moving to the next page
this.hideNextButton();
var that = this;
(function(){that.clickNextButton();}).delay(5);
I don't need the hiding button function or the delay, but just wanted to include an example of how it is used.
Any help is much appreciated, thanks in advance!
Here is a simplified version that works (updated to hide NextButton):
Qualtrics.SurveyEngine.addOnload(function() {
$('NextButton').hide();
document.on("keydown", function(e) {
if (e.keyCode === 13) $('NextButton').click();
});
});
It depends on the scope, or specifically where the function clickNextButton resides.
If you don't bother with the timeout you should be able to just remove the word 'that' from your Qualtrics.SurveyEngine function and it should work fine.
It's possible the function is not available in your current scope. So if removing 'that' doesn't work. Put it back in and put var that = this; in the line before your function call. It's far from a tidy way to do things at all but it may fix things for you.
Worth reading this.
http://www.w3schools.com/js/js_scope.asp
Didn't Meatloaf say something like... I'd do anything for scope.... but I don't do THAT?
As said in my comment...See if it solves your error
Qualtrics.SurveyEngine.addOnload(function()
{
document.addEventListener("keydown", function(e) {
if (e.keyCode === 13) {
function(){
that.clickNextButton();
}
}
} ); // here was a missing bracket here
});
So I have a video embedded in a question and I needed to disable to Next button for 15 seconds in that way I would know that autoplay video was watched.
And this worked for me so well:
Qualtrics.SurveyEngine.addOnload(function()
{
//Hides the next button and displays the question
//for 15 seconds before moving to the next page
this.disableNextButton();
var that = this;
(function(){that.enableNextButton();}).delay(15);
});
You can change the (15) seconds to any number, the Next Button will be activated and ready to be clicked next, but not automatically send you to next page.

Javascript onclick event not working in IE8

I have a button in our app that, when you click it, brings up a pop-up window asking if you are sure you want to proceed. Normally, that code would be in our HTML, but for this particular popup, it must be in Javascript. Anyway, the pop-up works just fine in Firefox, Chrome, and IE9, but it does NOT work in IE8. It is extremely frustrating. Does anyone have any ideas on how to fix this? Here is my code:
function graphicalAppConfirm() {
var graphical = $('#application_graphical').is(':checked');
if (graphical == true) {
$('.default_action').attr('onclick', "return confirm('This setting cannot be undone. Are you sure you wish to continue?')");
}
else {
$('.default_action').removeAttr('onclick');
}
}
I tried using the onmousedown event instead, and that made the popup appear, but then it would not go away.
Try using bind and unbind click. You don't necessarily care about the attributes.
function graphicalAppConfirm() {
var graphical = $('#application_graphical').is(':checked');
if (graphical == true) {
$('.default_action').click(function() { return confirm('This setting cannot be undone. Are you sure you wish to continue?'); });
} else {
$('.default_action').unbind('click');
}
}
If you're using jQuery 1.7+ then on/off is recommended instead of bind/unbind. See the documentation http://api.jquery.com/off/
Update: Here is an example with jQuery 1.8 which you can modify for your own usage. You'll probably want to perform the on/off functions when the checkbox is changed so that is how this example works.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
</head>
<body>
<button id="theone">Does nothing...</button>
<label for="check"><input id="check" type="checkbox" />Enable Button</label>
<div id="output" style="display:none;">Click registered.</div>
<script>
function callback() {
$("#output").show().fadeOut("slow");
}
$("#check").change(function() {
if (this.checked) {
$("body").on("click", "#theone", callback)
.find("#theone").text("Click Me Enabled!");
} else {
$("body").off("click", "#theone", callback)
.find("#theone").text("Click Me Disabled");
}
});
</script>
</body>
</html>
You can figure out the rest from there. You can test and see it work in IE 8 http://jsbin.com/ojejar/6

Javascript to make background image clickable?

I can't use a div because the CMS I am using won't allow html into the theme style (it's using a weird structure in its coding) and the only thing that I found that has worked is javascript but I don't know what javascript code will enable a clickable background image.
Any ideas?
<meta name="description" content="description here">
<script type="text/javascript">
document.backgroundImage = "url('http://mydomain.com/image.jpg')";
function callback() {
location.href = "http://mylink.com";
}
document.addEventListener("click", callback, false);
</script>
<script type="text/javascript"> //google analytics code </script>
this is the background of something right? This something has to receive the click event handler.
cheers.
edit: adding example:
Hypothesis:
o.id = "OhMyCuteness";
o.style.backgroundImage = "url('...')";
then:
o.addEventListener("click", callback, false);
and:
function callback(clickEvent) {
alert("They clicked meeeee buhuhuhu: " + clickEvent.target.id);
}
Edit2: in the case your document has a background this is exactly the same, use the document instead of the element "o" as a target for addEventListener.

Create a dual function html Url Link?

Problem:
You have a regular set of URL links in a HTML page e.g.:
Foo Bar
You want to create a JavaScript function such that when any HTML links are clicked, instead of the client's browser navigating to that new URL "/foo/bar" a JavaScript function is executed instead (e.g. this may for example make an Ajaxian call and load the HTML data without the need to reload the page).
However if the JavaScript is disabled OR a spider crawls the site, the UTL links are maintained gracefully.
Is this possible? Does it already exist? What's the usual approach?
EDIT 1:
These are some great answers!
Just a follow on question:
If the user clicks on the back button OR forward button, this would naturally break (as in it would go back to the last physical page it was on as opposed to one that was loaded).
Is there any way (cross browser) to maintain the back/forward buttons?
(e.g create an array of links clicked and over ride the browser buttons and use the array to navigate)?
<script type="text/javascript">
function your_function() {
alert('clicked!');
}
</script>
<a onclick="your_function();" href="/foo/bar">Foo Bar</a>
If Javascript is off, the link behaves normally.
In this case, unless your_function() does not return false, the link will be followed when clicked as well.
To prevent this, either make your_function() return false, or add return false; just after the function call in your onclick attribute:
<script type="text/javascript">
function your_function() {
alert('clicked!');
return false;
}
</script>
<a onclick="your_function();" href="/foo/bar">Foo Bar</a>
Or:
<script type="text/javascript">
function your_function() {
alert('clicked!');
}
</script>
<a onclick="your_function(); return false;" href="/foo/bar">Foo Bar</a>
Using element.addEventListener()
With default anchor behaviour following click:
<script type="text/javascript">
document.addEventListener("load", function() {
document.getElementById("your_link").addEventListener("click", function() {
alert('clicked');
}, true);
}, true);
</script>
<a id="your_link" href="/foo/bar">Foo Bar</a>
Without:
<script type="text/javascript">
document.addEventListener("load", function() {
document.getElementById("your_link").addEventListener("click", function(event) {
event.preventDefault();
alert('clicked');
}, true);
}, false);
</script>
<a id="your_link" href="/foo/bar">Foo Bar</a>
Given current HTML and W3C APIs, I would go for:
<script src="linkify.js"> </script>
in the markup, with linkify.js containing something like:
window.onload= function() {
document.addEventListener('click', function(ev) {
ev.preventDefault();
var el = ev.target;
if (el.tagName === 'A') {
// do stuff with el.href
}
}, false);
};
See e.g. http://jsfiddle.net/alnitak/nrC7G/, or http://jsfiddle.net/alnitak/6necb/ for a version which doesn't use window.onload.
Note that this code uses a single listener function registered on the document object, which will act on every <A> tag on the page that doesn't trap clicks for itself.
Use an onclick attribute:
click?
The return false prevents the default behaviour, in the absence of JavaScript, however, the link will be followed.
function do_whatever (e)
{
e.preventDefault ();
// do whatever you want with e.target
}
var links = document.getElementsByTagName ("a");
for (var i=0; i<links.length; ++i)
links[i].addEventListener ('click', do_whatever);
http://jsfiddle.net/bTuN7/
All done inside script and it won't 'hurt' if JavaScript doesn't work.
If you think about AJAX, then you have to know, that googlebot tries to parse it. http://www.youtube.com/watch?v=9qGGBYd51Ts
You can code like:
$('a').click(function() {
doSomethingWithURL($(this).attr('href'));
return false;
});
JavaScript is not executed in case it's disabled or if it's some web crawler, so from my point of view this is preferable.
There's quite a few methods out there such as this:
http://www.malbecmedia.com/blog/development/coding-a-ajax-site-that-degrades-gracefully-with-jquery/
Remember, though, that by virtue of a well setup server and caching you're not going to gain yourself much performance with an Ajax Load.

Categories