jHtmlArea event handling of keypress - javascript

I'm currently developping a text-to-symbol conversion tool (non-profit), and I'm having this problem:
For the WYSIWYG-editting of the text, I'd like to use a nice small wysiwyg editor (like jHtmlArea). This editor will show floating divs, so I'll have to intercept a lot of keypresses (spaces/arrows/etc)
Currently, my html area is loaded like this:
<script type="text/javascript">
$(function() {
$("#txtCustomHtmlArea").htmlarea({
loaded: function() {
$(this.editor).keydown(function(event) {
if(event.keyCode == 32) {
this.pasteHTML('<b>test</b>');
return false;
}
return true;
});
}
The problem with this code is that this.editor doesn't have the method pasteHTML. How can I use this method from this(=htmlarea).event?
This is most probably a fairly beginner question, but I'm really clueless towards where to look.
Thank you

Here's how I do it:
$("#my-text-area").htmlarea({
loaded: function () {
$.myControl = { jhtmlarea: this };
}
});
Then I can reference:
$($.myControl.jhtmlarea.editor.body).keypress(function (e) { });
This also gives me a handle to my the html area object from outside of the iFrame.

I think you're maybe getting yourself confused with the use of 'this' (I am definitely struggling to keep track of what it refers to!).
As a test, can you replace the
this.pasteHTML(...)
with
$("#txtCustomHtmlArea").pasteHTML(...)
or maybe
$("#txtCustomHtmlArea").editor.pasteHTML(...)
and see if that helps?

Related

How can I trigger jquery event at random time intervals?

I created a header using jquery.flip.js, found at https://github.com/nnattawat/flip. The plugin allows several ways to trigger the flip, the two relevant ones are 'click' and 'hover'. I was hoping to have the div's flip at random intervals automatically. I did find a similar question on stackoverflow that Heretic Monkey suggested using a recursive approach (Trigger mouse click and random intervals)...
var clickHand = function() {
$("[id^='hand_'].handIcon").trigger('click');
setTimeout(clickHand, (Math.random() * 3000) + 32000);
}
clickHand();
EDIT: sorry for not being clear. In the jquery code, the following method (?) handles the flip on click, however what I would like to do is have the divs flip automatically (if possible) without a hover or click to trigger. I tried using a setTimeout inside attachEvents, but it seemed to cause an issue with the styling.
attachEvents: function() {
var self = this;
if (self.setting.trigger === "click") {
self.element.on($.fn.tap ? "tap.flip" : "click.flip", $.proxy(self.clickHandler, self));
} else if (self.setting.trigger === "hover") {
self.element.on('mouseenter.flip', $.proxy(self.hoverHandler, self));
self.element.on('mouseleave.flip', $.proxy(self.unflip, self));
}
},
I am pretty new to javascript and am having a difficult time with this and any help would be appreciated.
I created a simple codepen, demonstrating the 3D flip, https://codepen.io/coeyflyer/pen/eYZGymG.
Thank you for any suggestions,
C

Using localStorage() to save a "closed" state on modal so it doesn't show for that user again

I have a pop-over modal that I am loading on my page on load, I would like to make it once it's closed to not show up again for that user. I've done similar things with localStorage(); but for some reason can't figure out the syntax to make this work.
I tried a solution where it sets a class, but on refresh it will reload the original element, so now I am trying this idea where I change the state of of the modal to "visited". Any ideas what I could be missing to get this to work in the same way I'm hoping?
localStorage function:
$(function() {
if (localStorage) {
if (!localStorage.getItem('visited')) {
$('.projects-takeover').show();
}
} else {
$('.projects-takeover').show();
}
$('.projects-close').click(function() {
$('.projects-takeover').fadeOut();
});
localStorage.setItem('visited', true);
return false;
});
Here is a jsfiddle with the code implemented as well, thanks for the help!
You javascript code is correct. Good thing you added a jsfiddle as the problem becomes very easy to identify - the modal's style is set in such a way that it is always visible. Simply change the display property to nonе in the .projects-takeover class and it should work. Check out the updated fiddle
Try this ->
$(function() {
var pt = $('.projects-takeover'); //i just hate repeating myself.
if (localStorage) {
if (!localStorage.getItem('visited')) {
pt.show();
} else {
pt.hide(); //this bit was missing
}
} else {
pt.show();
}
$('.projects-close').click(function() {
pt.fadeOut();
});
localStorage.setItem('visited', true);
return false;
});

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
});

Error: "Too much recursion"

Firebug shows me the following error: too much recursion , I tried a lot to determine what causes me this error, but in vain
This is my JavaScript code:
$(".scan").click(function(e){
e.preventDefault();
var docName = $("#nomPJ").val();
$(this).attr("nomDoc",docName);
});
Another on a separated js file:
$(".scan").live("click",function(event){
alert("frame");
var e = event.target;
nomDoc = $(e).attr("nomDoc");
idDoc = $(e).attr("idDoc");
alert("id"+idDoc);
$("#title").text(nomDoc);
$("#modal-body").empty().append('<iframe frameBorder="0" height="90%" width="98%" style="margin-left: 5px" src="/GRH/Scan.jsp?nomDoc=' + nomDoc + '&idDoc='+idDoc+'"></iframe>');
$("#myModal").modal({ dynamic: true });
});
The html element:
numériser
I removed to first code, but the problem still remains.
Ok, sound like a bug, but I have readed the docs and there is not dynamic option, anyway, is well know that the modal bootstrap plugin has some other bugs like the multiple modal bug.
Posible solutions:
Modify the modal.js which is not recommended
Use another modal plugin. It seems like it works pretty well.
Merge the two click events into one
Delete the dynamic: true option on modal() function, set a fixed width to #myModal and overflow:scroll using css.
For those of you trying to actually troubleshoot this in some other application, firebug/fox is pretty rough; chrome will help you out a lot more.
If you're feeling your oats, or can't use chrome, this post saved me from a ton of hassle!
long story short, it goes through logging each function automatically, so
function apples () {
bananas()
}
function bananas () {
apples()
}
becomes
function apples () {
console.log('apples');
bananas()
}
function bananas () {
console.log('bananas');
apples()
}
so that you can see exactly which functions are wrapped up in the all-to-vague "too much recursion"
happy troubleshooting!

JQuery Multi File event not firing

I have the following code in aspx
<input id="fileControl" type="file" class="multi" name="fileControl"/>
and
$(document).ready(function () {
var fileSelections = [];
$('#fileControl').MultiFile({
onFileAppend: function () {
//$('#F9-Log').append('<li>onFileAppend - '+value+'</li>')
fileSelections.push(value);
},
onFileSelect: function () {
fileSelections.push();
},
afterFileSelect: function () {
fileSelections.push();
},
afterFileAppend: function () {
fileSelections.push();
}
});
});
I have added the following files as part of jQuery multifile plugin
jquery.MetaData.js
jquery.MultiFile.js
jquery.MultiFile.pack.js
But when I add or remove a file the events are not fired. Why is this?
I ran into this same issue and the problem is that if you want to subscribe to events, you can't set the class in the input element.
So, your input element should look like this:
<input id="fileControl" type="file" name="fileControl"/>
Then it should work.
I imagine this isn't an issue for you anymore, but in case this is ever needed by anyone else.
Just seen this.... have updated the documentation accordingly
http://www.fyneworks.com/jquery/multiple-file-upload/
I can hardly find the time to keep the docs up to date, but this is a huge issue (the reason behind most support queries I receive) so thanks for pointing it out!

Categories