I know that it's impossible to thwart the world's most advanced minds, but I'd like to put the slightest of barriers on my website to keep my students from copying text from it and posting that text as their answer. (If they hand type it, that's ok).
I'm just so afraid of JavaScript because of cross browser inconsistencies.
Given that I have jQuery loaded and prefer to use jQuery whenever possible, how do I:
Disable Ctrl + c
Disable Menu Edit Copy.
Its some how daunting to create a function that would do that, what you should target is, clearing the clipboard so even if, the user press Ctrl + C, nothing is copied into the clipboard, a simple function like this should do the trick :
<script language="javascript">
function clearData(){
window.clipboardData.setData('text','')
}
function cldata(){
if(clipboardData){
clipboardData.clearData();
}
}
setInterval("cldata();", 1000);
</script>
<body ondragstart="return false;" onselectstart="return false;" oncontextmenu="return false;" onload="clearData();" onblur="clearData();">
although this can still be defeated....
Just add the following code right before closing </HEAD>
tag of your web page:
<script>
function killCopy(e){
return false;
}
function reEnable(){
return true;
}
document.onselectstart=new Function ("return false");
if (window.sidebar){
document.onmousedown=killCopy;
document.onclick=reEnable;
}
</script>
I would suggest you to use:
<div oncopy="return false;">Here you have protected text</div>
Support for this method could be found here: http://help.dottoro.com/ljwexqxl.php
It is simple and in my opinion sufficient against regular users. To be honest there is no option to fully prevent copying text. One can always use for example Chrome Developer Tools and copy even dynamically loaded text from there.
For more effective protection you should place oncopy in <body> tag because otherwise it is possible to copy text by starting selection from outer <div>.
If you have your texts in particular divs, you could put a transparent div on top of those divs. Secondly, you could make all your protected text dynamic, and inject it into the divs from javascript where is would exist in a coded form -- that would defeat a 'view-source'.
<script type="text/javascript" language="javascript">
$(function() {
$(this).bind("contextmenu", function(e) {
e.preventDefault();
});
});
</script>
<script type="text/JavaScript">
function killCopy(e){ return false }
function reEnable(){ return true }
document.onselectstart=new Function ("return false");
if (window.sidebar)
{ document.onmousedown=killCopy;
document.onclick=reEnable; }
</script>
//By using above code you right click will be disabled as well as no one can copy your page content
A simple and valid solution - bind to the 'copy' event and prevent it. You can also set what text will be copied (and later pasted by the user).
document.addEventListener('copy', function (e){
e.preventDefault();
e.clipboardData.setData("text/plain", "Do not copy this site's content!");
})
Selecting text, copy, the right click can be disabled on a web page easily using jQuery. Below is the simple jQuery code snippet which can do this task easily:
<script type="text/javascript">
// Disable right click on web page
$("html").on("contextmenu",function(e){
return false;
});
// Disable cut, copy and paste on web page
$('html').bind('cut copy paste', function (e) {
e.preventDefault();
});
</script>
Source: Disable right click, copy, cut on web page using jQuery
To achieve that you need to block mouse click and context menu click on your webpage.
Here is a sample code:
<script language="JavaScript1.2">
var msgpopup="COPYING CONTENT IS PROHIBITED";
function handle(){
if(toShowMessage== "1") alert(message);
if(closeSelf== "1") self.close();
return false;
}
function mouseDown() {
if (event.button == "2" || event.button == "3"){handle();}
}
function mouseUp(e) {
//if (document.layers || (document.getElementById && !document.all)){
if (e.which == "2" || e.which == "3"){ handle();}
//}
}
document.onmousedown=mouseDown;
document.onmouseup=mouseUp;
document.oncontextmenu=new Function("alert(msgpopup);return false")
</script>
You can put the text in an input tag attributed as readonly and prevent the user from copy using JS. So, user cannot copy it even from developer menu.
Related
I have a function that is triggered by "Calculate" button
I need this line to only run once per session (session could be 1 day or until browser is reloaded).
$('.popup-with-form').magnificPopup('open');
This opens a Magnific Popup. Once this function is executed (popup opens), if "calculate" button is pressed again, I don't want popup to open again.
JS / JQuery code:
function StateChanged() {
if (XmlHttp.readyState == 4 || XmlHttp.readyState == "complete") {
$('.popup-with-form').magnificPopup('open');
document.getElementById("CalcSum").innerHTML = XmlHttp.responseText;
document.getElementById("CalcSumPopup").innerHTML = XmlHttp.responseText;
}
}
PS I know many of these questions pop up, and I tried different ways of doing thing, but since I'm "code-challanged" and do not know JQuery or JS I can't figure it out. I know there is a .one "thing" in JQuery, but don't understand how to make it work.
If you want to execute this line only once per browser session you can use sessionStorage. When you set a variable on sessionStorage it keeps its value until the browser closes (e.g. until you close Google Chrome).
So you can do something like:
if (!sessionStorage.alreadyClicked) {
$('.popup-with-form').magnificPopup('open');
sessionStorage.alreadyClicked = 1;
}
Be careful with sessionStorage because it can only store string values.
If you want the line to be executed only once per page session (which means once every page refresh) then you can use any variable and set it to true to remember you already executed the line:
if (!window.alreadyClicked) {
$('.popup-with-form').magnificPopup('open');
alreadyClicked = true;
}
Try
Edit, v2
I read about .one but could not figure it out :( ... I actually need
it to run once ONLY when CALCULATE button is pressed. – Roofing
Calculator
html
<!-- removed `action="javascript:GetInfo();"
, accept-charset="UNKNOWN"
, enctype="application/x-www-form-urlencoded"
, method="post"`
from `form` attributes -->
<form id="formcalc" style="text-align: left;">
<!-- changed `input` `type` to `button` -->
<input name="calculate" type="button" value="Calculate" />
</form>
js
$("#formcalc > input[name='calculate']")
.one("click", function(e) {
e.stopPropagation();
GetInfo();
});
v1
$("a.popup-with-form").one("click", function(e) {
// do stuff, once
// i.e.g.,
// `XmlHttp.onreadystatechange = StateChanged;` at `ShowSum()`
$(e.target).remove(); // remove element when `click`ed once
});
jsfiddle http://jsfiddle.net/guest271314/7K3tn/
See http://api.jquery.com/one/
Please use below.
disableOn
null
If window width is less then number in this option - lightbox will not be opened and default behavior of element will be triggered. Set to 0 to disable behavior. Option works only when you initialize Magnific Popup from DOM element.
Can also accept Function as a parameter, which should return true if lightbox can be opened andfalse otherwise. For example:
disableOn: function() { if( $(condition) { return false; } return true; }
Question:
I am running a function where you press the keys C or M using the keypress() function and every time I press one of those keys, the letter is marked automatically in Firefox. Is there a way to disable this using JavaScript or is this something Firefox does by default?
I have tried to look for an answer using Google but it seems no one has had this issue before using the keypress() function in JS.
Code:
<script type="text/javascript">
$(document).ready(function()
{
var once = false;
$(window).keypress(function(e)
{
if(!once)
{
if (e.which == 99)
{
once = true;
$("input#left").val( 1 );
$("form").submit();
}
else if (e.which == 109)
{
once = true;
$("input#right").val( 1 );
$("form").submit();
}
}
});
});
</script>
Thanks in advance for any tips!
Just call preventDefault():
$(window).keypress(function(e)
{
e.preventDefault()
// other code
}
There are a few ways of handling this. If you call e.preventDefault() you should be covered, however that's not your only option.
HTML5 introduced many new tags and attributes into markup, one of them being an autocomplete attribute for text fields. If you add this to your HTML (<input type='text' id='myInput' autocomplete='off'>) you should be covered as well. You can't always rely on your user having support for HTML5, but this is still an easy solution to your problem.
It can't hurt you to implement both of these small changes in your code.
I am having this code:
Add
is there any way to make an alert whenever the user will press this button without changing the code or adding onclick event?
You can simple overwrite the attribute with JavaScript:
// Select the targeted element(s), in this case the first <a> element
// Note: You will need to replace this by a code that works
// for your actual markup!
document.getElementsByTagName("a")[0].onclick = function() {
alert("hi");
return false;
};
Demo: http://jsfiddle.net/WNZAP/
As the OP states that they are not allowed to change the HTML, and that jquery is not available to them.
Not having an 'id' on the link makes life very difficult. So the following code presumes the link is the very first one on the page...
Place this javascript into the <head></head> section of your page...
<script type="text/javascript">
window.onload = function() {
document.getElementsByTagName("a")[0].onclick = function() {
alert("Hello World");
return false;
}
}
</script>
See Live JSFiddle Demo
It's not possible to trigger an action without an event. But if I get your question right you want to trigger an alert without changing the HTML.
The easiest way would be by using a JavaScript library like jQuery. So load the library either by downloading it and placing it in your project or through the Google CDN:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
And then do something like this:
<script type="text/javascript">
$(document).ready(function(){
$(".submitme").click(function(){
alert("hello world");
});
});
</script>
I have two divs. One on the left and one on the right.
The one on the left will display links and whenever clicked, the content will appear on the right div.
I've been trying to do it with Iframe and javascript but I can't seem to get it right. I'm still a beginner and I have been searching all over the internet sigh.
Any ideas?!
Thanks
You have a couple choices in order to achieve this.
The easiest way is to have all the content separated in divs with an id in the right div. Hide all but the first link. The links on the left would have these ids linking to the corresponding content. When a link is clicked hide all, to clear the right div, and show the id that was clicked.
The other choice is AJAX which isn't as accessible as the first choice since if Javascript is off it won't work. For the first choice if Javascript is off the content will just be displayed and upon clicking the links it will scroll to the content.
You can use the DOM to achieve something like that...have a look at http://www.w3schools.com/jsref/default.asp it has some good examples there...
If you want to display information in another DIV, you should use AJAX. If you would like to use a navigation frame, check this.
You can easily do this by using the jQuery and jQuery UI library. http://jqueryui.com/demos/tabs/#ajax The jQueryUI tabs can load remote content.
In your link's onClick, you can change the src of the iframe to the link's href and that should automatically change the iframe's contents.
Hey Jasmin, you could do something like this. Please note this solution is without a javascript framework. But you should definetly look into a framework lik jquery or prototype.
Let's say you have:
<html><head>...</head><body>
<ul>
<li><a href="www.google.com" id="firstLink" >GOOGLE</a></li>
<li><a href="www.twitter.com" >Twitter</a></li>
<li><a href="www.tumblr.com" >Tumblr</a></li>
</ul>
<div><iframe name="TEST" src="about:blank" id="ts" ></IFRAME></div>
PUT THE SCRIPT TAG CLOSE TO THE BOTTOM OF YOU PAGE FOR SAKE OF PAGESPEED
BETTER PUT EVERYTHING IN AN EXTERNAL JS SCRIPT
<script laguage='javascript'>
addLoadListener(initEvents);
function initEvents()
{
var mylink = document.getElementById("firstLink");
mylink.onclick = changeFrame(mylink.href);
return true;
}
function changeFrame(url)
{
//OPEN URL IN IFRAME WITH ID = ts
document.getElementByID('ts').src=url;
return false; // IS NEEDED TO SKIP THE NORMAL BEHAVIOUR OF THE LINK
}
// THIS FUNCTION IS NEEDED TO HAVE THE JS READY WHEN THE PAGE IS LOADED
function addLoadListener(fn)
{
if (typeof window.addEventListener != 'undefined')
{
window.addEventListener('load', fn, false);
}
else if (typeof document.addEventListener != 'undefined')
{
document.addEventListener('load', fn, false);
}
else if (typeof window.attachEvent != 'undefined')
{
window.attachEvent('onload', fn);
}
else
{
var oldfn = window.onload;
if (typeof window.onload != 'function')
{
window.onload = fn;
}
else
{
window.onload = function()
{
oldfn();
fn();
};
}
}
</script>
</body></html>
I have seen the following methods of putting JavaScript code in an <a> tag:
function DoSomething() { ... return false; }
link
link
link
link
I understand the idea of trying to put a valid URL instead of just JavaScript code, just in case the user doesn't have JavaScript enabled. But for the purpose of this discussion, I need to assume JavaScript is enabled (they can't login without it).
I personally like option 2 as it allows you to see what's going to be run–especially useful when debuging where there are parameters being passed to the function. I have used it quite a bit and haven't found browser issues.
I have read that people recommend 4, because it gives the user a real link to follow, but really, # isn't "real". It will go absolutely no where.
Is there one that isn't support or is really bad, when you know the user has JavaScript enabled?
Related question: Href for JavaScript links: “#” or “javascript:void(0)”?.
I quite enjoy Matt Kruse's Javascript Best Practices article. In it, he states that using the href section to execute JavaScript code is a bad idea. Even though you have stated that your users must have JavaScript enabled, there's no reason you can't have a simple HTML page that all your JavaScript links can point to for their href section in the event that someone happens to turn off JavaScript after logging in. I would highly encourage you to still allow this fallback mechanism. Something like this will adhere to "best practices" and accomplish your goal:
go
Why would you do this when you can use addEventListener/attachEvent? If there is no href-equivalent, don't use an <a>, use a <button> and style it accordingly.
You forgot another method:
5: Link
With the JavaScript code:
document.getElementById('myLink').onclick = function() {
// Do stuff.
};
I can't comment on which of the options has the best support or which is semantically the best, but I'll just say that I much prefer this style because it separates your content from your JavaScript code. It keeps all the JavaScript code together, which is much easier to maintain (especially if you are applying this to many links), and you can even put it in an external file which can then be packed to reduce filesize and cached by client browsers.
link
I will do this, or:
link
(document.getElementById("Link")).onclick = function() {
DoSomething();
return false;
};
Depending on the situation. For larger apps, the second one is best because then it consolidates your event code.
Method #2 has a syntax error in FF3 and IE7.
I prefer methods #1 and #3, because #4 dirty the URI with '#' although causes less typing...
Obviously, as noted by other responses, the best solution is separate html from event handling.
One difference I've noticed between this:
<a class="actor" href="javascript:act1()">Click me</a>
and this:
<a class="actor" onclick="act1();">Click me</a>
is that if in either case you have:
<script>$('.actor').click(act2);</script>
then for the first example, act2 will run before act1 and in the second example, it will be the other way around.
Modern browsers only
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function(doc){
var hasClass = function(el,className) {
return (' ' + el.className + ' ').indexOf(' ' + className + ' ') > -1;
}
doc.addEventListener('click', function(e){
if(hasClass(e.target, 'click-me')){
e.preventDefault();
doSomething.call(e.target, e);
}
});
})(document);
function doSomething(event){
console.log(this); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me">Button 1</button>
<input class="click-me" type="button" value="Button 2">
</body>
</html>
Cross-browser
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function(doc){
var cb_addEventListener = function(obj, evt, fnc) {
// W3C model
if (obj.addEventListener) {
obj.addEventListener(evt, fnc, false);
return true;
}
// Microsoft model
else if (obj.attachEvent) {
return obj.attachEvent('on' + evt, fnc);
}
// Browser don't support W3C or MSFT model, go on with traditional
else {
evt = 'on'+evt;
if(typeof obj[evt] === 'function'){
// Object already has a function on traditional
// Let's wrap it with our own function inside another function
fnc = (function(f1,f2){
return function(){
f1.apply(this,arguments);
f2.apply(this,arguments);
}
})(obj[evt], fnc);
}
obj[evt] = fnc;
return true;
}
return false;
};
var hasClass = function(el,className) {
return (' ' + el.className + ' ').indexOf(' ' + className + ' ') > -1;
}
cb_addEventListener(doc, 'click', function(e){
if(hasClass(e.target, 'click-me')){
e.preventDefault ? e.preventDefault() : e.returnValue = false;
doSomething.call(e.target, e);
}
});
})(document);
function doSomething(event){
console.log(this); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me">Button 1</button>
<input class="click-me" type="button" value="Button 2">
</body>
</html>
You can run this before the document is ready, clicking the buttons will work because we attach the event to the document.
Sources:
Test if an element contains a class?
event.preventDefault() function not working in IE
https://gist.github.com/eduardocereto/955642