Fire an event before `cut` event in ace editor - javascript

I want to fire an event before cut, so that I can get what text is being cut i.e. what has been already selected. I am currently using the following code, which doesn't seem to work as desired.
$("#editor").bind({
cut:function(){
console.log('Cut Detected');
alert(editor.selection.getRange());
}
});
editor is the id of the "div" tag which is editable. editor.selection.getRange() returns the start and end of selection.
edit I am woring with content editable div and want to apply the functionality on it.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Editor</title>
</head>
<body>
<div id='myTa' contenteditable>hello world where are you</div>
<script type='text/javascript' src='jquery-2.1.4.min.js'></script>
<script type='text/javascript'>
$("#myTa").on("cut", function(){
alert(this.selectionStart+ " to " + this.selectionEnd);
})
</script>
</body>
</html>

You are correct that you need to use the cut event. The ClipboardEvent API is apparently unstable but yes, I would have thought it would include the text being moved onto the clipboard.
The following works for me:
$("textarea").on("cut", function(){
alert(this.value.substring(this.selectionStart, this.selectionEnd));
})
It's worth noting that bind is deprecated in jQuery, you should use on instead. Try out the snippet:
$("textarea").on("cut", function() {
alert(this.value.substring(this.selectionStart, this.selectionEnd));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>

I think at first that clipboardEvent will have the clipped text, but it seems not, so I try to find the selection related properties of input and found it.
And the reference is HTMLInputElement.
This codes work in presumption that your $("#editor") is either an input or textarea.
$("#editor").bind({
cut:function(e){
console.log('Cut Detected');
var $this = $(this);
var selectStart = this.selectionStart;
var selectionEnd = this.selectionEnd;
var clippedValue = $this.val().slice(selectStart, selectionEnd);
// Now you have the clipped value, do whatever you want with the
// value.
alert(clippedValue);
}
});
For works on contentediable, you can do this, which I just found info from Return HTML from a user-selected text and MDN
$("#myTa").on("cut", function(e){
// Seems diff bro
var selections = window.getSelection();
var currentSelection = selections.getRangeAt(0);
var start = currentSelection.startOffset;
var end = currentSelection.endOffset;
var selectedContents = currentSelection.toString();
// Do whatever you want.
console.log(start, end);
console.log(selectedContents);
alert(selectedContents);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id='myTa' contenteditable>ask;ndjkasn asdbasj aujs d sdib askjbnsaab asbh mjn a</div>

I have got the solution to my answer. apperently there is an editor.on('cut',function(e)) in ace editor I use
editor.on("cut", function(e){
console.log('Cut Detected');
console.log(editor.selection.getRange());
});

Related

javascript delete file on unlimited upload button

thanks for the upcoming assistance, I am working on a uploader and trying to add a javascript delete link to each extra input field. I have one that adds a child.
here is a codepen: http://codepen.io/anon/pen/NPPmYP
What I am wanting to do is during creation of the extra input fields, Here is my code if anyone is able to help.
I also tried these methods and they didnt work
<script language="javascript">
<!--
function _add_more() {
files.appendChild(document.createElement("br"));
var del = document.createTextNode("Delete ");
document.getElementById("files").appendChild(del);
var extra = document.createElement('input');
extra.type="file";
extra.id="images[]";
extra.name="images[]";
extra.size="50";
extra.accept="image/jpeg";
document.getElementById("files").appendChild(extra);
}
</script>
I tried changing what I have for that line into
var del = document.createTextNode('delete ');
But it just showed it as text instead of making it a clickable link, I am really unsure on how to create the function to remove a child without effecting any others. Thank you for the upcoming support
You'll need to attach an event handler to the click of the delete link.
Something like this. (Updated as per comment)
<script language="javascript">
function _add_more() {
var del = document.createElement("a");
del.appendChild(document.createTextNode("Delete"));
del.href="#"; // Apply link styling
var extra = document.createElement('input');
extra.type="file";
extra.id="images[]";
extra.name="images[]";
extra.size="50";
extra.accept="image/jpeg";
var additionalFile = document.createElement('span');
additionalFile.appendChild(document.createElement("br"));
additionalFile.appendChild(del);
additionalFile.appendChild(extra);
document.getElementById("files").appendChild(additionalFile);
del.addEventListener('click', function(event){
additionalFile.parentElement.removeChild(additionalFile);
event.preventDefault();
});
}
</script>

creating a list in html using jQuery append not working

I've been staring at this code for hours now, any input appreciated.
I want to create a list in a HTML file from an array of objects using jquery append, but it justs stays blank.
HTML:
<html>
<head>
<script src="jquery-1.10.0.js"></script>
<script src="test.js"></script>
<title></title>
</head>
<body>
<div id="list">
</div>
<div id="template">
<div class="info">
<a class="url"></a>
</div>
</div>
</body>
</html>
Script:
function update(events) {
var eventList = $('#list');
eventList.empty();
events.forEach(
function(_event) {
var eventsHtml = $('#template .info').clone();
eventsHtml.find('.url').text(_event.title)
.attr('href', _event.url);
eventList.append(eventsHtml);
});
}
var events = [{title:'fu',url:'bar'}, {title:'bar',url:'fu'}];
update(events);
Assuming the JS code you show is contained in test.js, either move this line:
<script src="test.js"></script>
...to the end of the body (just before the closing </body> tag), or wrap your code in a $(document).ready() handler.
The way you currently have it, this line:
var eventList = $('#list')
...doesn't find the '#list' element because the script runs before the element is parsed. Same problem with finding '#template .info'.
You could wrap all of the code in a ready handler, or if you need to be able to call the update() function from elsewhere just wrap the initial call:
$(document).ready(function() {
var events = [{title:'fu',url:'bar'}, {title:'bar',url:'fu'}];
update(events);
});
Use the following JS code:
$(document).ready(function(){
var events = [{title:'fu',url:'bar'}, {title:'bar',url:'fu'}];
var eventList = $('#list');
eventList.empty();
events.forEach(
function(_event) {
var eventsHtml = $('#template .info').clone();
eventsHtml.find('.url').text(_event.title)
.attr('href', _event.url);
eventList.append(eventsHtml);
});
});

Javascript Onclicks not working?

I have a jQuery application which finds a specific div, and edit's its inner HTML. As it does this, it adds several divs with onclicks designed to call a function in my JS.
For some strange reason, clicking on these never works if I have a function defined in my code set to activate. However, it works fine when calling "alert("Testing");".
I am quite bewildered at this as I have in the past been able to make code-generated onclicks work just fine. The only thing new here is jQuery.
Code:
function button(votefor)
{
var oc = 'function(){activate();}'
return '<span onclick=\''+oc+'\' class="geoBut">'+ votefor +'</span>';
}
Elsewhere in code:
var buttons = '';
for (var i = 2; i < strs.length; i++)
{
buttons += button(strs[i]);
}
var output = '<div name="pwermess" class="geoCon"><div class="geoBox" style=""><br/><div>'+text+'</div><br/><div>'+buttons+'</div><br/><div name="percentages"></div</div><br/></div>';
$(obj).html(output);
Elsewhere:
function activate()
{
alert("Testing");
}
You may want to take a look at jQuery.live(eventType, eventHandler), which binds an event handler to objects (matching a selector) whenever they are created, e.g.:
$(".somebtn").live("click", myClickHandler);
Follows a dummy example, may be this can help you.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="http://cdn.jquerytools.org/1.2.5/jquery.tools.min.js"></script>
<script type="text/javascript">
$(function() {
$('.go-right').click(function(){
c="Hello world";
$("#output").html(c);
});
});
</script>
</head>
<body >
<div id="output"></div>
<a class="go-right">RIGHT</a>
</body>
</html>
Change this:
var oc = 'function(){activate();}'
To be this instead:
var oc = 'activate();'

Robust Way of Selecting All Text in Textbox

I'm trying to have the content of the an HTML textbox be selected fully onFocus.
I know the simple solution of putting a onfocus="this.select()" on the component but this is not a good solution because if a user double clicks into the area the selection is lost and in browsers like chrome it is rarely working like it should and just reverts into input form.
I have searched on Google for a little while and can't find a good solution, most suggestions are of this simple solution.
What I would like it is that the selection inside the textbox not change once selected and if possible the user should not be able to edit the content of the textbox, for example if you have used AdSense when you grab code from AdSense the selection never changes and your unable to alter the code in the textbox.
Any solutions would be appreciated.
Sounds like you want the the text box to be read-only. However, I would say that preventing the user from changing the selection is a bad idea: it's confusing and inconvenient for the user, so I haven't implemented that. The following will select the input's content when focussed in all browsers, and the input is read-only:
<input type="text" id="foo" readonly value="Some text">
<script type="text/javascript">
var textBox = document.getElementById("foo");
textBox.onfocus = function() {
textBox.select();
// Work around Chrome's little problem
textBox.onmouseup = function() {
// Prevent further mouseup intervention
textBox.onmouseup = null;
return false;
};
};
</script>
I altered the code by Tim Down to get it work the way it should, here is the final code for other people ( make sure to capitalize O in readOnly ).
<script type="text/javascript">
function selectAll(id) {
var textBox = document.getElementById(id);
textBox.select();
textBox.readOnly = true;
textBox.onmouseup = function() {
textBox.select();
return false;
};
textBox.onmousedown = function() {
textBox.select();
return false;
};
};
</script>
<html>
<body>
<script>
function getElement(elemname)
{
if (document.getElementById)
return document.getElementById(elemname);
else if (document.all)
return document.all[elemname];
return 0;
}
function lockingSelect()
{
ta = getElement("mytext");
ta.select();
ta.readonly = true;
}
</script>
<textarea id = "mytext"></textarea>
<br>
<input type=button onclick="lockingSelect();" value="lock"/>
</body>
</html>

cloneNode in internet explorer

While executing the following code IE throws the error -- Object doesn't support this property or method -- referring to the cloneNode() method. 'i' is the loop counter, source and dest are both HTML select elements.
dest.options[dest.options.length] = source.options[i].cloneNode( true );
FF and Chrome behave as expected. Any ideas on how to get IE to execute cloneNode()? The IE 8 debugger shows source.options[i] does have a cloneNode() method.
Thanks.
IE requires the
new Option()
construct.
document.createElement( 'option' );
or
cloneNode()
will fail. Of course, all options work as expected in a proper web browser.
Actually, cloneNode isn't throwing any error. Break your code down into smaller chunks to properly identify the source of the error:
var origOpt = source.options[i];
var clonedOpt = origOpt.cloneNode( true ); // no error here
var destOptLength = dest.options.length;
dest.options[destOptLength] = clonedOpt; // error!
dest.options.add(clonedOpt); // this errors too!
dest.appendChild(clonedOpt); // but this works!
Or, putting it back the way you had it, all on one line:
dest.appendChild(source.options[i].cloneNode( true ));
I've found this post useful: IE’s cloneNode doesn’t actually clone!
<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Untitled Document</title>
<style>
p, select,option{font-size:20px;max-width:640px}
</style>
<script>
function testSelect(n, where){
var pa= document.getElementsByName('testselect')[0];
if(!pa){
pa= document.createElement('select');
where.appendChild(pa);
pa.name= 'testselect';
pa.size= '1';
}
while(pa.options.length<n){
var i= pa.options.length;
var oi= document.createElement('option');
pa.appendChild(oi);
oi.value= 100*(i+1)+'';
oi.text= oi.value;
}
pa.selectedIndex= 0;
pa.onchange= function(e){
e= window.event? event.srcElement: e.target;
var val= e.options[e.selectedIndex];
alert(val.text);
}
return pa;
}
window.onload= function(){
var pa= testSelect(10, document.getElementsByTagName('h2')[0]);
var ox= pa.options[0];
pa.appendChild(ox.cloneNode(true))
}
</script>
</head>
<body>
<h2>Dynamic Select:</h2>
<p>You need to insert the select into the document,
and the option into the select,
before IE grants the options any attributes.
This bit creates a select element and 10 options,
and then clones and appends the first option to the end.
<br>It works in most browsers.
</p>
</body>
</html>

Categories

Resources