Closure not working in ZeroClipboard - javascript

I have the following JS code for ZeroClipBoard :
onComplete: function(item) {
var text= $(item).html();//Not working when I hover the clip
//var text= 'Hello';// This is working when I hover the clip
var clip = new ZeroClipboard.Client();
clip.setHandCursor(true);
clip.addEventListener('complete', function(client, text) {
debugstr("Copied text to clipboard: " + text );
});
clip.addEventListener('mouseOver', function(client) {
clip.setText(text);
})
// glue specifying our button AND its container
clip.glue('id_clip_button', 'id_clip_container');
},
Above oncomplete is oneofmy function which is called on some action . I get item from it which is html element.
Now in the above code :
var text= $(item).html();//Not working when I hover the clip
//var text= 'Hello';// This is working when I hover the clip
If I comment the first line and uncomment the second line the clip is working and text is getting copied to clipboard . But I have to use the value of that html element while copying the text . So how should I go with this ? I am getting the value of control at this point
var text= $(item).html();//
But when the hover function is called it is lost. I was thinking that it will be preserved via Closure. Am I missing something ? I am not able to get the value of text at this line :
clip.setText(text);
I am not able to access any variable from outside when I am inside clip.addEventListener('mouseOver', function(client) { clip.setText(text); })

The value won't be preserved in the function call, you need to use a $.proxy instead:
clip.addEventListener('mouseOver', $.proxy(function(client) {
// "this" is now set to text
clip.setText(this);
}, text));

Related

Filling a select box of a form using the text inside the <option> tags with CasperJS

I would like to fill the "Acheter un billet" form of this site : http://www.leguichet.fr/
This is what I've done so far :
var casper = require('casper').create();
casper.start('http://www.leguichet.fr/', function() {
this.fill('form#search_tickets', {'departure':'1', 'arrival':'2'}, false);
this.click('input[value="Rechercher"]');
this.wait(1000, function() {
this.echo(this.getCurrentUrl());
});
});
casper.run(function(){
this.exit();
});
The documentation says that fill() uses the value attribute to match against but I would like to use the text inside the option tags. For instance they have :
<option value="Montpellier">Montpellier</option>
<option value="Montpellier">Béziers</option>
Thus if I want to select Béziers I have to write 'departure':'Montpellier'.
Is there a way to use the text inside the option tags?
The easiest way would be to retrieve the element value of the option that you want to select and use that value later. It may be the case that during the subsequent selection another option is selected, but the value will be the same, so it should not make a difference:
var x = require('casper').selectXPath;
casper.start('http://www.leguichet.fr/', function() {
var textToSelect = "Béziers";
var value = this.getElementAttribute(x("//form[#id='search_tickets']//select[#name='departure']/option[contains(text(), '" + text + "')]"), 'value');
this.fill('form#search_tickets', {'departure': value, 'arrival':'2'}, false);
this.click('input[value="Rechercher"]');
this.wait(1000, function() {
this.echo(this.getCurrentUrl())
});
});
You can easily select DOM nodes with XPath by testing their text content with the text() function. Do the same thing for arrival.

Making a part of an uploaded text file as clickable using javascript

I uploaded one file using javascript. I want to make some parts of the text file as highlighted as well as clickable. For example: I want to make all the "hello" in the uploaded file as clickable and highlighted.
I am able to highlight the text as i have used button tag and changed its background and border property in css but I am unable to do an onclick action when the button is clicked.
I tried it like this:
var sel_data=$("#sel").text(); // for taking the text file in avariable
var str='hello';
//making the regular expression of str
var re = new RegExp(str,"g");
//For replacing the 'str' by highlighted and clickable 'str'
var re_str="<button class='highlight' id='ty' onclick='alertfunc()' value="+str+">"+str+"</button>"
//replacement of 'str' by highlighted and clickable 'str'
var rep_data=sel_data.replace(re,re_str);
sel_data=rep_data;
//function to be executed when the button will get clicked
function alertfunc() {
alert('yellow');
}
I also tried it like this
var str='hello'
var re_str="<button class='highlight' id='ty' value="+str+">"+str+"</button>"
$(".highlight").click(function(){
alert("yellow");
})
or like this
var button = document.getElementById("ty");
button.onclick = function(){
alert("yellow");
}
But none of them is working , Please suggest
I referred the above examples by this link: Html make text clickable without making it a hyperlink
There are just a few things wrong here.
First, execute this code on document ready :
$(document).ready(function(){
// code
});
Then, update the actual html in the DOM :
//replacement of 'str' by highlighted and clickable 'str'
var rep_data=sel_data.replace(re,re_str);
sel_data=rep_data;
$("#sel").html(sel_data); // here
And use event delegation for the click :
$("#sel").on('click', '.highlight', function(){
alert("yellow");
});
demo
This is done by using jQuery library and the ready snippet :contains.
Here is the code you need:
jQuery.fn.highlight = function (str, className) {
var regex = new RegExp(str, "gi");
return this.each(function () {
$(this).contents().filter(function() {
return this.nodeType == 3 && regex.test(this.nodeValue);
}).replaceWith(function() {
return (this.nodeValue || "").replace(regex, function(match) {
return "<span class=\"" + className + "\">" + match + "</span>";
});
});
});
};
Using this snippet will lead the words "hello" to be wrapped around a span with class of your choice.
Now to call this function all you need to do is:
$(".testHighlight *").highlight("hello", "highlight");
Ofcourse you have to setup the .testHighlight class with CSS to be something like:
.testHighlight {
background:yellow;
}
To make them clickable you can do it easily with jQuery:
$(.testHighlight).click(function(){
//YOUR CODE HERE
});
You can check more on this snippet here.

Javascript .append() with .fadein()

I created a function that adds text to an element called #textBox. I want the text to fade in the box so, here is my code.
var addText_3 = function(text) {
$("#textBox").append("<p><i>" + text + "</i></p>").hide().fadeIn(500);
};
So, my function appends to text and hides it so it can fade in. However, I just want the appended element to fade in. When I try this function, all of the other text in the element also fade. Is there a way to only make the element I am appending to fade in?
$("<p><i>" + text + "</i></p>").appendTo("#textbox").hide().fadeIn(500);
Create the new element, append it to #textbox, and fade it in.
var text = 'Stack Overflow';
$("<p><i>" + text + "</i></p>").appendTo("#textbox").hide().fadeIn(500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="textbox">Some text</div>
The chaining of function does not return what you expect : it returns #textBox while you thought it'll returns your freshly created text node.
So, you have to call both the hide() and fadeIn() functions on your text node instead.
appendTo() is the function you'd rather use as it returns the caller (call it on your new node).
Example (with jQuery's clean node creation) :
var addText_3 = function(text) {
var text_node = $("<p>").append($("<i>", {html: text})).hide(); //Can use text instead of html
text_node.appendTo("#textBox").fadeIn(500);
};
This one's my personal pref
DEMO
var text = 'asdfasdfasdf';
$("<p><i>" + text + "</i></p>").fadeIn(500).appendTo($('#textBox'));

Clear title property while JQuery tooltip shows

I am using some very simple JQuery to create a hovering tool tip using text stored in elements' title attribute. It's working okay, but I need to stop the browser's default title behaviour occurring at the same time (or after the slight delay on hover).
I think JQuery's .on() functionality may not be the best way, although I am trying to use the latest functionality (that I am aware of!).
Currently if I clear the existing title value, the actual tooltip appears but is empty. I think that is because the code runs continuously while the mouse is over the element.
Can anyone offer a way to stop the browser's title text appearing, but restore the original value of title onmouseout? I need the code to work with JQuery 1.10.1+ with XHTML1.1 compatibility.
Thanks.
$(document).ready(function () {
$('<div/>', { id: 'ttfloat', 'class': 'tooltip' }).appendTo('body');
BuildTipsV3();
});
function pageLoad() { // fired by ASP.NET after partial postback
BuildTipsV3();
}
//var temptt;
function BuildTipsV3() {
$("[title]").on({
mouseenter: function () {
var o = $(this).offset();
var y = o.top + 18;
var x = o.left;
temptt = $(this).attr("title"); // temp storage
$(this).data('title', temptt);
//$(this).attr('title', '');
var tooltip = temptt;
tooltip = tooltip.replace(/(\r\n|\n|\r)/gm, "<br/>");
$("#ttfloat").css({top:y, left:x})
.html(tooltip)
.show();
},
mouseleave: function () {
$("#ttfloat").hide();
$(this).attr('title', $(this).data('title')); // reset for accessibility
}
});
}
Try making these lines:
temptt = $(this).attr("title"); // temp storage
$(this).data('title', temptt);
//$(this).attr('title', '');
var tooltip = temptt;
do this instead:
var $this = $(this),
tooltip = $this.attr('title') || $this.data('title');
$this
.attr('title', '')
.data('title', tooltip);
What the code above does is that if the title attribute is empty, the or (||) operator will then look for the title within the data.
Use $(selector).removeAttr('title'); to achieve your desired results.

Insert value into TEXTAREA where cursor was

I have a textarea and a div with values. When I click on a value I insert it into textarea. I need it to be inserted where my cursor was in textarea. Why do I say WAS? Because when I move it out and click on a value to insert, I assume it looses focus in the text area.
So, my question is, is there a way to "remember" the latest cursor position within textarea and then insert my values at that position?
Perhaps it could be a char number in a string?.. Currently I add it like this:
input.val( function( i, val ) { return val + " " + myInsert + " "; } );
Also I use jQuery, perhaps I could use it?
I've written a cross-browser jQuery plug-in for dealing with the caret/selection in textareas and text inputs called Rangy inputs (terrible name, I really should think of a better one). A combination of methods from this and the techniques in Edgar Villegas Alvarado's answer should do the trick, although in IE, the focusout event fires too late and you'll need to use the proprietary beforedeactivate event instead:
var $textBox = $("#foo");
function saveSelection(){
$textBox.data("lastSelection", $textBox.getSelection());
}
$textBox.focusout(saveSelection);
$textBox.bind("beforedeactivate", function() {
saveSelection();
$textBox.unbind("focusout");
});
When inserting text later, the following will insert text at the previous cursor position (or overwrite the previously selected text, if the user had selected any):
var selection = $textBox.data("lastSelection");
$textBox.focus();
$textBox.setSelection(selection.start, selection.end);
$textBox.replaceSelectedText("Some new text");
See jsFiddle example here: http://jsfiddle.net/rQXrJ/1/
Here is a working example of what you are trying to do check it out at:
http://jsfiddle.net/J5Z2n/1/
Hello there my good friend....
how do you do
the jQuery:
function insertAt (myField, myValue, startSel, endSel) {
if (startSel || startSel == '0') {
var startPos = startSel;
var endPos = endSel;
myField.val(myField.val().substring(0, startPos)+ myValue+ myField.val().substring(endPos, myField.val().length));
}
else {
myField.val() += myValue;
}
}
// calling the function
var targetBox = $('textarea#insert'),
startSel,
endSel;
targetBox.bind('focusout', function() {
//insertAtCursor(this, 'how do you do');
startSel = this.selectionStart;
endSel = this.selectionEnd;
});
$("#myvalue").click(function() {
var myValue = $(this).text();
insertAt(targetBox, myValue, startSel, endSel);
});
The original function was borrowed from this post
http://alexking.org/blog/2003/06/02/inserting-at-the-cursor-using-javascript
That should give you a solid head start I hope. Cheers
If the caret (the cursor) is somewhere in the text field, it registers in Javascript as an empty selection. That is, the selectionStart and selectionEnd attributes are the same. You can use those attributes to detect the position of the caret.
Apparently selectionStart and selectionEnd are quite useful here. Check this out:
http://www.scottklarr.com/topic/425/how-to-insert-text-into-a-textarea-where-the-cursor-is/
You can use the jQuery Caret plugin to get/set the cursor position .
Example usage:
var cursorPosition = $("#textbox").caret().start);
You could 'store' this position like this:
$("#textbox").focusout(function(){
var cursorPosition = $(this).caret().start);
$(this).data("lastCursorPos", cursorPosition);
});
To retrieve it (on your div click event), do this:
var lastCursorPosition = $("#textbox").data("lastCursorPos");
Hope this helps. Cheers

Categories

Resources