I'm using hammer.js for gesture functionality on my web application. I have used it to swipe a video element and it works perfect as expected. However, when I apply the following code to an image element it's not working.
App.Views.Photo = Backbone.View.extend({
template : template('photoTemplate'),
className : 'photo',
parent : null,
events: {
'swipe' : 'swiped',
// 'pan' : 'dragged'
},
...
swiped: function(e) {
this.remove();
this.parent.newContent(this.model);
},
This exact same code is working for the video elements but not for the images. I also tried doing e.gesture.preventDefault(); inside the swiped function but that didn't work either. I'm testing the application on firefox at the moment.
Any help will be appreciated.
Thanks
[EDIT]: I'm initializing the hammer code as follows
render: function() {
$(this.el).attr('id', this.model.attributes._id);
this.$el.html( this.template( this.model.toJSON() ) );
this.$el.hammer();
return this;
},
You can use:
<img draggable="false"...
Or in CSS like this (May not be supported by all browsers, esp IE)
pointer-events: none;
Ok, so after banging my head on this problem for weeks I finally got the answer.
in the initialize function I placed the following code
$('img').on('dragstart', function(event) { event.preventDefault(); });
So it looks like this
initialize: function(opts) {
this.render();
this.parent = opts.parent;
$('img').on('dragstart', function(event) { event.preventDefault(); });
},
What this does is that it prevents the image from being dragged like default and that did the trick.
And now on swipe the image gets removed like I wanted.
[EDIT]
If you have multiple images on the page add this to the event like
this.$('img').on('dragstart', function(event) { event.preventDefault(); });
This will apply to all of the picture that are rendered with that view.
Related
So I am trying to avoid JQUERY UI or really any libraries JS wise and am trying to create some drag and drop functionality in backbone.JS. I've already been able to have some success as you can see at www.smartkrawl.com on the left side but cannot get tables to move in the canvas section. Here is a snippet of code that listens for a mousedown event to execute a draggable function but if you view the source code of the site the JS files, particularly ocoa-tables.js, are available. Any help would be GREATLY appreciated.
var Table = Backbone.Model.extend({
initialize:function(options){
this.set("x",options.x);
this.set("y",options.y);
this.set("el",options.el);
$('body').on('mousedown','.table', function() {
console.log('mousedown')
});
}
});
You probably should use view for this instead of model. So make each table as a separate view, then use events hash to add listeners instead of delegating it on the body
var TableView = Backbone.View.extend({
events: {
"mousedown": "_onMouseDown"
},
_onMouseDown: function(e) {
console.log('mousedown')
}
});
var firstTable = new TableView({ el: ".first.table" });
var secondTable = new TableView({ el: ".second.table" });
I'm not familiar with backbone.js though I do feel like I have a decent grasp on jQuery. I hope I'm not asking an obvious question, though if it's the table that you want, why not directly target the table?
$(".table").on("mousedown", function() {
...
});
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
});
I'm using classed links to change FlowPlayer content. Here is a working version: http://jsfiddle.net/r9fAj/
In my actual page using the same code the first link clicked works fine. The second one does not fire the click function at all. Even if I comment out everything but the console.log()...
$('.playerLink').click( function() {
audioPlayer.unload();
initAudioPlayer();
$('#player').css('display', 'block');
$('#player').animate({"height":"50px"}, 1000);
var newClip = {'url':$(this).attr('ajax-data'),'autoplay':true};
audioPlayer.play(newClip);
console.log('playing ' + $(this).attr('ajax-data'));
});
HTML like so
Listen
Listen
<a id="flowplayer" href="/audio/episodes/09_27_2013_Happy_Hour_88509726.mp3"></a>
And the player initialized like so:
var audioPlayer;
var initAudioPlayer = function () {
$f("flowplayer", "/player/flowplayer-3.2.16.swf", {
plugins: {
controls: {
fullscreen: false,
autoHide: false,
}
},
clip: {
autoPlay: false,
url: "",
}
});
audioPlayer = $f();
};
initAudioPlayer();
Since the jsFiddle works over and over I assume something else in my page is preventing the second click() from working but the console has no errors for me.
So my question is, short of posting the whole site's code how do I pursue debugging this?
So it sounds like your .click() event handler is only being fired for the first link you click and not for additional clicks. For general debugging, you could take your page that is not working and gradually comment out / remove other part of the JS and HTML until you are able to make it work correctly. Or start with the minimal amount that is working (the fiddle) and gradually add in the rest to see when it stops working.
So this is the first site I have done where content is delivered via AJAX and internal links are caught by
$("a:not([href^='http://'])").click( function(e) {
var url = $(this).attr("href");
var title = ($(this).attr("title")) ? ': ' + $(this).attr("title") : '';
e.preventDefault();
if(url!=window.location){
window.history.pushState({path:url},title,url);
$('#contentMain').load(url);
document.title = "It's New Orleans" + title;
}
});
For some reason it does work once to click a link with the class but the second time gets preventDefault()ed.
Listen
The fix was adding [href^='#'] to not() e.g.
$("a:not([href^='http://'],[href^='#'])").click( function(e) {
I'm opening a Backbone view in a Zurb Foundation Reveal (Modal) section.
this.$('#ChangeIconModal').html( this.editIconView.render().el );
This works fine the first time. However, if I close it (either by clicking it, or by calling $('#ChangeIconModal').foundation('reveal', 'close')), the click event I have set up no longer fire.
Here is how I've set up my click event:
events: { 'click button.finish': 'finish', 'click a.close-reveal-modal': 'close' }
And, regardless of how the close happens, I remove the Backbone view when I'm done with it:
this.remove();
Does anything seem obviously wrong with what I'm doing?
PS - I'm new to the whole Backbone/Zurb world, so bear with me. If you need any more information, I'll be glad to provide it, I just don't know what to provide.
Ahh, I figured it out. Here's what I did, in case anyone else comes across the same issue.
Here's what I had before in my view:
initialize: function() {
// Other initialize code here...
this.editIconView = new IconEditView({ model: this.model });
}
iconEdit: function() {
this.$('#SubtabEditModal').html( this.editIconView.render().el );
}
However, because I called remove on it later, the reference to editIconView was no longer valid.
I had to change my code to be more like this:
initialize: function() {
// Other initialize code here...
}
iconEdit: function() {
this.editIconView = new IconEditView({ model: this.model });
this.$('#SubtabEditModal').html( this.editIconView.render().el );
}
It seems to be working now. If this isn't clear, leave a comment, I'll try to help.
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...