JavaScript Fullscreen API plugin - javascript

I've found a plugin called screenfull.js and I'm wondering if it's possible to automatically open the page in fullscreen without clicking on a button.
This is an example of code for making the page fullscreen :
document.getElementById('#button').addEventListener('click', function() {
if ( screenfull ) {
screenfull.request();
} else {
// Ignore or do something else
}
});

Using their demo, you could just run the request on window load:
e.g.
window.onload = function() {
screenfull.request( $('#container')[0] );
};
[edit]
You could also run this with jQuery document ready...
E.g.
$(document).ready(function() {
screenfull.request( $('#container')[0] );
});

No, that is not possible. The requestFullScrenn() must be triggered by a direct user action (like a click) for security considerations. It's just the same as with popups.
Read https://wiki.mozilla.org/Security/Reviews/Firefox10/CodeEditor/FullScreenAPI and maybe https://wiki.mozilla.org/Gecko:FullScreenAPI for reference.

I use a trick...
I listen for any click on the body to activate.
Eg:
$('body').on('click', '*', function() {
screenfull.request();
});
N.B.: It does not track buttons (e.t.c) that already have event handlers...

Related

Disable browser back action using jquery

I am developing an online testing app and it is required that during the test, users cannot be allowed to refresh page neither go back until the test is ended. I have successfully been able to disable refresh action in jquery through all means possible (to the best of my knowledge) using the following code:
$(window).bind({
beforeunload: function(ev) {
ev.preventDefault();
},
unload: function(ev) {
ev.preventDefault();
}
});
But I have been having troubles disabling the back action on all browsers, the best solution I got on SO conflicts with the code I have above, it is given below:
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
//alert("Reloaded");
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload forthis.
};
}
else {
var ignoreHashChange = true;
window.onhashchange = function () {
if (!ignoreHashChange) {
ignoreHashChange = true;
window.location.hash = Math.random();
// Detect and redirect change here
// Works in older FF and IE9
// * it does mess with your hash symbol (anchor?) pound sign
// delimiter on the end of the URL
}
else {
ignoreHashChange = false;
}
};
}
}
The solution above suits my purpose in disabling the back button but conflicts with the page refresh prevention handler above.
I am out of ideas on what to do and I have also searched a long time for a solution to this but found none yet. Any help would be greatly appreciated, even if it takes a totally different approach to solving the problem, I wouldn't mind at all.
Thanks everyone
UPDATE
I never realized that doing things this way breaks a lot of ethical rules, anyway, I've thought about it and figured out something else to do when if the page is refreshed or back button pressed (either using keyboard or the browser controls). I want to redirect to a url which will end the current exam session. I believe that's possible, hence I think the solution I seek is to get the best way to achieve this. Redirecting to another url if back button or refresh button is pressed (both using the browser controls and the keyboard).
I have tried many options but none worked except this-
//Diable Browser back in all Browsers
if (history.pushState != undefined) {
history.pushState(null, null, location.href);
}
history.back();
history.forward();
window.onpopstate = function () {
history.go(1);
};
With regards to the update I posted in my question, I have been able to solve my problem. Here's what I did (just modifying my existing code a little and removing the window.onload listener I had initially):
$(window).bind({
beforeunload: function(ev) {
window.location.replace("my_url_goes_in_here");
},
unload: function(ev) {
window.location.replace("my_url_goes_in_here");
}
});
This construct works for both page refresh and back actions done in anyway (either using keyboard or browser controls for the any of them).
However, I've not yet tested in any other browser other than firefox 47.0, but I'm glad it's working for now all the same.
Thanks for all your comments, they were extremely helpful
Using javascript if you have two pages page1 and page2 and (page1 redirect to page2) and you want to restrict the user from getting back to page1, just put this code at page1.
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
function disableBack() {
window.history.forward()
}
window.onload = disableBack();
window.onpageshow = function (evt) {
if (evt.persisted)
disableBack()
}
});
</script>

Using jquery to control the iframe URL [duplicate]

I have an iframe on a page, coming from a 3rd party (an ad). I'd like to fire a click event when that iframe is clicked in (to record some in-house stats). Something like:
$('#iframe_id').click(function() {
//run function that records clicks
});
..based on HTML of:
<iframe id="iframe_id" src="http://something.com"></iframe>
I can't seem to get any variation of this to work. Thoughts?
There's no 'onclick' event for an iframe, but you can try to catch the click event of the document in the iframe:
document.getElementById("iframe_id").contentWindow.document.body.onclick =
function() {
alert("iframe clicked");
}
EDIT
Though this doesn't solve your cross site problem, FYI jQuery has been updated to play well with iFrames:
$('#iframe_id').on('click', function(event) { });
Update 1/2015
The link to the iframe explanation has been removed as it's no longer available.
Note
The code above will not work if the iframe is from different domain than the host page. You can still try to use hacks mentioned in comments.
I was trying to find a better answer that was more standalone, so I started to think about how JQuery does events and custom events. Since click (from JQuery) is just any event, I thought that all I had to do was trigger the event given that the iframe's content has been clicked on. Thus, this was my solution
$(document).ready(function () {
$("iframe").each(function () {
//Using closures to capture each one
var iframe = $(this);
iframe.on("load", function () { //Make sure it is fully loaded
iframe.contents().click(function (event) {
iframe.trigger("click");
});
});
iframe.click(function () {
//Handle what you need it to do
});
});
});
Try using this : iframeTracker jQuery Plugin, like that :
jQuery(document).ready(function($){
$('.iframe_wrap iframe').iframeTracker({
blurCallback: function(){
// Do something when iframe is clicked (like firing an XHR request)
}
});
});
It works only if the frame contains page from the same domain (does
not violate same-origin policy)
See this:
var iframe = $('#your_iframe').contents();
iframe.find('your_clicable_item').click(function(event){
console.log('work fine');
});
You could simulate a focus/click event by having something like the following.
(adapted from $(window).blur event affecting Iframe)
$(window).blur(function () {
// check focus
if ($('iframe').is(':focus')) {
console.log("iframe focused");
$(document.activeElement).trigger("focus");// Could trigger click event instead
}
else {
console.log("iframe unfocused");
}
});
//Test
$('#iframe_id').on('focus', function(e){
console.log(e);
console.log("hello im focused");
})
None of the suggested answers worked for me. I solved a similar case the following way:
<iframe id="iframe_id" src="http://something.com" allowtrancparency="yes" frameborder="o"></iframe>
The css (of course exact positioning should change according to the app requirements):
#iframe-wrapper, iframe#iframe_id {
width: 162px;
border: none;
height: 21px;
position: absolute;
top: 3px;
left: 398px;
}
#alerts-wrapper {
z-index: 1000;
}
Of course now you can catch any event on the iframe-wrapper.
You can use this code to bind click an element which is in iframe.
jQuery('.class_in_iframe',jQuery('[id="id_of_iframe"]')[0].contentWindow.document.body).on('click',function(){
console.log("triggered !!")
});
This will allow you to target a specfic element in the iframe such as button or text fields or practically anything as on method allows you to put selector as an argument
$(window).load(function(){
$("#ifameid").contents().on('click' , 'form input' , function(){
console.log(this);
});
});
Maybe somewhat old but this could probably be useful for people trying to deal with same-domain-policy.
let isOverIframe = null;
$('iframe').hover(function() {
isOverIframe = true;
}, function() {
isOverIframe = false;
});
$(window).on('blur', function() {
if(!isOverIframe)
return;
// ...
});
Based on https://gist.github.com/jaydson/1780598
You may run into some timing issues depending on when you bind the click event but it will bind the event to the correct window/document. You would probably get better results actually binding to the iframe window though. You could do that like this:
var iframeWin = $('iframe')[0].contentWindow;
iframeWin.name = 'iframe';
$(iframeWin).bind('click', function(event) {
//Do something
alert( this.name + ' is now loaded' );
});
This may be interesting for ppl using Primefaces (which uses CLEditor):
document.getElementById('form:somecontainer:editor')
.getElementsByTagName('iframe')[0].contentWindow
.document.onclick = function(){//do something}
I basically just took the answer from Travelling Tech Guy and changed the selection a bit .. ;)
Solution that work for me :
var editorInstance = CKEDITOR.instances[this.editorId];
editorInstance.on('focus', function(e) {
console.log("tadaaa");
});
You can solve it very easily, just wrap that iframe in wrapper, and track clicks on it.
Like this:
<div id="iframe_id_wrapper">
<iframe id="iframe_id" src="http://something.com"></iframe>
</div>
And disable pointer events on iframe itself.
#iframe_id { pointer-events: none; }
After this changes your code will work like expected.
$('#iframe_id_wrapper').click(function() {
//run function that records clicks
});

Clicking a link programmatically after using preventDefault()?

I'm trying to change a href link programmatically (according to a result from an ajax async operation) and open it in a new window (I don't want to use window.open as it behaves like a popup and being blocked in IE).
The following code works only after clicking MANUALLY on the link for a second time, how can I make it work on the first click?
Simplified example:
trying to change href link dynamically
<script type="text/javascript">
document.getElementById('link').addEventListener("click", function (e) {
if (!e.target.hasAttribute("target")) //only preventDefault for the first time..
{
e.target.setAttribute("target", "_blank");
e.preventDefault();
updateLink();
}
});
function updateLink() {
// --HERE I PERFORM AN AJAX CALL WHICH TAKES A WHILE AND BY ITS RESULT I DECIDE WHICH URL TO USE - BUT HERE I JUST USE IT HARDCODED--
document.getElementById('link').setAttribute("href", "http://google.com");
document.getElementById('link').click();
}
I organized your code in this jsFiddle: http://jsfiddle.net/mswieboda/Hhj4D/
The JavaScript:
var $link = document.getElementById('link');
$link.addEventListener("click", function (e) {
if (!e.target.hasAttribute("target")) {
//only preventDefault for the first time..
e.target.setAttribute("target", "_blank");
e.preventDefault();
updateLink();
}
});
function updateLink() {
$link.setAttribute("href", "http://google.com");
$link.click();
}
This worked for me when I ran it. Hovering the link, you could see http://demo.com but clicking it takes you to http://google.com. Is this the desired functionality? You can definitely use the updateLink function any time (after an AJAX call) to change the href, also, you could probably set the _target in that function as well, makes more sense to me that way.

What is the proper method for creating dynamic hyperlinks in JavaScript?

I know it's frowned upon to create links such as link text as this tricks the user into thinking it's a real link.
I have quite a few links that actually just run JS code in the browser instead of forcing page navigation, and as such I don't want to use the above and am looking for an alternative that works in all browsers and prevents middle clicking from opening a new tab/ window.
Would the following approach be satisfactory?
HTML
link text
JavaScript
$("#id_here").bind('click',(function(params){
return function(){
// do stuff here with `params`
};
})(params));
javascript: anything is bad. There isn't much difference between the two javascript: uses above. Using "#" for the href is about as bad; it adds to the history with JS off and the link is not useful. What you should do (ideally) is have the link actually work, e.g.
<a href="/an/actual/path"> ...
Then, with JS, prevent default link behavior
$("#id_here").on('click', function (e) { e.preventDefault(); });
If there is no actual path to go to, then the link should not even be exposed with JS off; you can either append it to the DOM later or just hide it with CSS (and show it with JS).
I would recommend you used another node other than <a>, such as a <div>:
<div id="jsLink" style="cursor:pointer">Click Me</div>
and jQuery:
$("#jsLink").click(function(params){
// do something
}
link text
# is here to make a link look like link
JavaScript:
$("#id_here").bind('click',function(e){
e.preventDefault();
})
e.preventDefault() does not allow browser to execute default action (like navigate to another page)
I did some playing around, and you can get some good results with hashchange:
var commands = {
foo: function() { alert("Foo!"); },
bar: function() { alert("Foo bar!"); },
baz: function() { alert("Foo bar baz!"); }
};
$(window).bind('hashchange', function() {
var hash = window.location.hash.replace(/^#/,'');
if(commands[hash]) {
commands[hash]();
return false;
}
}).trigger('hashchange');​
With the simple HTML of:
Foo
Bar
Baz​
This even works if you right click -> open in new tab or middle click!
Note that hashchange is not supported by all browsers.

Disable a next/previous button(link) temporarily when clicked in jQuery Cycle plugin (not necessarily a jquery cycle issue)

I need to prevent link from being clicked for let's say 2 seconds.
Here is an example http://jsbin.com/orinib/4/edit
When you look at the rendered mode you see next and prev links. When you click next, it slides with a nice transition. However if you click multiple times there is no transition sort of, which is expected. But my question: is this how can I prevent clicking on the next link, for about 2 seconds (or what ever time it takes for transition to happen) so that no matter what transition will occur.
This is what I tried to use, but did not work:
function(){
var thePreventer = false;
$("#next").bind($(this),function(e){
if(!thePreventer){
thePreventer = true;
setTimeout(function(){
thePreventer = false;
}, 2000);
}else{
e.preventDefault();
}
});
}
Which I got from here "Disable" a link temporarily when clicked? I think. I believe that i cannot achieve this effect with this code (although it works on other links). I believe this is due to the fact that cycle-plugin got a hold of that link, and I understand that I have to bind/tap-into this functionality of the plugin. Please note: that this code may not work I just used it to show that I tried it and it did not work, you can reuse it if you have to or give me your own stuff.
Please help, if you can.
EDIT:
As mrtsherman proposed this simple yet elegant ANSWER: http://jsfiddle.net/LCWLb.
Take a look at the cycle options page. There are a number of ways to do this. I would consider using the pager event onPrevNextEvent. You can assign a callback function.
$('#slideshow').cycle({
pager: '#nav',
onPrevNextEvent: function(isNext, zeroBasedSlideIndex, slideElement) {
//disable controls
},
after: function(currSlideElement, nextSlideElement, options, forwardFlag) {
//reenable controls
}
});
The following will temporarily prevent clicks while a slideshow is running, as shown in this fiddle:
$.fn.extend({
delayClick: function(callback) {
this.bind('click', function(e) {
$self = $(this);
if( $self.hasClass('disabled') ) {
$('#log').append('<p>click prevented on '+$self.attr('id')+'</p>');
}
else {
$self.addClass('disabled');
callback.call(this, [arguments]);
setTimeout(function() {
$self.removeClass('disabled');
}, 1000);
}
return false;
});
}
});

Categories