EventListener cloning in userscript - javascript

I have this function:
function main() {
var bottomArea = document.getElementsByClassName("bottom-area");
for (var i = 0; i < bottomArea.length; i++) {
var showDialogLink = document.createElement("a");
showDialogLink.innerHTML = "link";
showDialogLink.onclick = function(){showSelect(this);return false;};
bottomArea[i].insertBefore(showDialogLink, bottomArea[i].childNodes[3]);
}
}
So far the code works just fine. When I click the newly created link, it calls showSelect(this) function just fine.
The problem is there is another userscript/browser extension (which I don't have access to - it's not mine), which basically clones whole another div in which 'bottom-area' div is nested. This is all right too, but the problem is that it doesn't clone my function trigger and those newly cloned instances (I'm not really sure what is their nature) of that link do no longer trigger showSelect(this) function. Only the first one created by my userscript does.
Is there some way in which I should add my function trigger on my link, that will stay even after cloning/copying?
EDIT: I'll just edit to show html tree:
This is at the beginning:
<div>
<div class="bottom-area"></div>
</div>
My userscript adds a link with an onclick eventlistener on the 'a' tag:
<div>
<div class="bottom-area"><a>link</a></div>
</div>
The other userscript basically clones it (there is a textarea inside the div and its value gets cloned too), but without the eventlistener, so clicking on the cloned links no longer triggers my function.
EDIT2: If it helps, the userscript I'm creating is a reddit userscript. I'm adding small functionality to commenting and adding a link right next to the 'reddiquette' link under the comment text field. That works with the pre-generated text field. However when I click 'reply' down the comment tree, the whole div together with text field, submit button and my link gets cloned under the comment I'm replying too, but my link no longer has the function trigger on itself.

The easiest solution may be to simply use HTML event attributes (instead of addEventListener), such as <a onclick="dostuff();">link</a>, because the attribute should be preserved during 'cloning'. See this fiddle (tested in Firefox 40) for an example.
Letting the code in the onclick attribute interact with your userscript may be be a little difficult because it runs in a different JavaScript environment. Luckily there's plenty of possible workarounds, depending on your exact needs.

Related

Generate Bootstrap tooltip on-the-fly

I have a page with a text and some words in the text can change dynamically. These words have an element and should have a tooltip. When the user hovers the word (or I guess on a touch device clicks it), a tooltip should be generated using generateSpecialMarkupElement($(element).text()). Once the HTML has been rendered to the DOM another JavaScript function has to be called replaceMarkupHTML().
I don't have control over these functions unfortunately.
Now I'm wondering if there is a simple way in bootstrap get this done. For instance a before event to run the first function and an after event to call the second one.
Here is a simple example text and simplified versions of the functions:
http://jsfiddle.net/8aqz5auk/1/
So is there a bootstrap-way of hooking/intercepting this kind of thing? Or is there maybe another simple way it could be done?
Edit: I just had an idea. When bootstrap shows a tooltip, it seems to inject an element into the DOM. The interesting part is the container with the class 'tooltip-inner'. So I tried to listen on the body for new elements matching '.tooltip-inner' to be injected and whenever that happens I try to manipulate it:
$('body').on('DOMNodeInserted', '.tooltip-inner', function () {
var el = $(this)
el.html("") // empty the tooltip element
el.append(generateSpecialMarkupElement(el.text())) // insert the generated markup element
replaceMarkupHTML() // replace the markup element with normal html
});
Unfortunately it doesn't work. It just throws a a million errors and the site freezes when I try it.
Edit 2:
Thanks to Chris Barr, I got a little bit closer: http://jsfiddle.net/8aqz5auk/2/
But the tooltip doesn't always show up and the position of the tooltip seems to be kind of wrong (shows up on top of the word, rather then next to/above/below/...).
You might want to look into the tooltip events listed in the docs: https://getbootstrap.com/docs/3.3/javascript/#tooltips-events
$('.elements-with-tooltips').on('show.bs.tooltip', function () {
// do something…
})
You can run a function: before being shown, after being shown, before hiding, after hiding, and when the element is inserted into the DOM.

Toggling an html IMG element's class using JS (no Jquery)

I give up... All of your answers were just different ways of targeting the local element.
If you bothered to actually read what I was saying you would realise that it was not a problem with the code I already had, just that the code DID NOT work on IMG tags.
While faffing around trying to demonstrate my problem (and that none of your solutions did anything different to what was already happening) I found that I can achieve exactly what I want by applying a Grayscale filter to a DIV element placed over each image. The mouseover event then triggers an opacity change in the DIV element.
It is a little heavier that I wanted but it answered my ACTUAL question. The answer being:
Yes, there probably is a way to toggle class of IMG tags. But no, I am probably not going to find it here without causing arguments or being told i'm using "bad code". So yes, it IS easier and more efficient to target DIV elements.
By the way, page load times are about how large data packages are. Larger data packages (images, html/css/js documents, etc) take longer to download and so the page takes longer to load. The website I am trying to create proves this thesis, I have an almost complete and (almost) fully functional website with loads of 'clever' little effects all under 20mb, about 15mb of which is images. This website is clean and simple, is hosted on my Samsung Galaxy Tab 4 (using Papaya) and loads almost instantly.
THIS is what I meant by "I want this to be VERY lite". Thank you all for your attempts to help, it's just a shame that I couldn't get anyone to understand what was going on.
If you add onClick to image element you don't need to pass anything, you will receive MouseEvent which contains all information. You need target from event.
I suggest to not use onClick on element as it is not scalable, you have to add it to all elements. Better to add listener to wrapping/container element and then filter target by some attribute e.g data-something Please check fiddle
So you have wrapping element and you images:
<div class="images-container">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150" data-toggleable class="thumb-gray thumb-color" />
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150" data-toggleable class="thumb-gray" />
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150" data-toggleable class="thumb-gray" />
</div>
and you attach listener to you wrapping element. It is best practice as you don't attach listeners to each element and same time you are able easily scale your solution
var imagesContainerEl = document.querySelector('.images-container');
imagesContainerEl.addEventListener('click', function(event) {
var element = event.target;
if (element.hasAttribute('data-toggleable')) {
element.classList.toggle('thumb-color');
}
});
The same code can be extended to support mouseover and mouseout. Check fiddle2. One function to rule them all and in the darkness bind them..
var imagesContainerEl = document.querySelector('.images-container');
imagesContainerEl.addEventListener('mouseover', onToggleImage);
imagesContainerEl.addEventListener('mouseout', onToggleImage);
function onToggleImage(event) {
var element = event.target;
if (element.hasAttribute('data-toggleable')) {
element.classList.toggle('thumb-color');
}
}
Also updated fiddle which shows how to make image grayscale/color
Is what you refer to in your question as
onClick="colorFunction(image1)"
an inline javascript event listener?
If so, try replacing it with:
onClick="colorFunction(this)"
and rewrite colorFunction() as:
function colorFunction(image) {
image.classList.toggle('thumb-color');
}

CKEditor, custom object with children

I am trying to create a plugin for CKEditor that adds a custom object with children.
Example:
<div>
<img src="someimage.jpg" />
<p>
Some text
<span>Some subtext</span>
</p>
<img src="someStaticImage.jpg" />
</div>
In the onOk function i have:
---snip---
this.imgElement.setAttribute('src',path + data.imageSrc);
this.staticImgElement.setAttribute('src',path + 'images/staticimg.jpg');
this.imgElement.appendTo(this.element);
this.imgElement.appendTo(this.element);
this.staticImgElement.appendTo(this.element);
---snip---
I would like for this block to behave as a single element, meaning that pressing backspace deletes the whole block, double clicking on it opens the edit dialog...
Any idea how i could do that?
I came close with setting
this.element.setAttribute('contenteditable','false');
However this doesn't allow content to be inserted before "it", if "it" was the first element in the ckedit window.
EDIT:
More info:
I'm using CKEditor 4.0, inline version
I wish for my "object" to be like the "image" plugin, where when you double click on the image, a dialog opens, the same one as when you create the object (where you set the src, width...).
I managed to make it similar to it, but because it is a div with child elements, CKEditor treats each part as seperate, which makes the deleting of the object (with backspace) behave in a wierd way, only parts of it get deleted, backspace needs to be pressed multiple times to delete the entire object.
I'm a CKEditor core developer and I think that I've got an interesting news for you :). Coincidentally, right now we're working on Widgets feature which is exactly what you mean.
Making some fragments of the page non-editable by setting contenteditable=false make them unusable. Selecting, copying&pasting, right clicking, using arrow keys - all this is at least partially broken. And it's even worse if you try to add a nested editable element (editable inside non-editable), because e.g. it can be deleted from inside.
That's why we decided to implement a nice API for creating widgets and fix all these bugs under the hood. Maybe not all bugs and in all browsers at the beginning, because there's huge (really... I mean huuuuge :P) amount of them and of course no standard behaviour between browsers at all. But it will be a good start. First version of widgets that will be released in upcoming CKEditor 4.2 should be usable - this is our goal. Then we'll focus on stabilizing the implementation.
PS. CKEditor Roadmap says that CKE 4.2 will be ready in 11 days and this is not true, unfortunately. We're delayed, but I don't want to estimate now how much.
You indicated that you've created the plugin that handles the object, but that the problem you want to solve is the inability to insert content before the object when it's the first item.
It looks like this bug report is about this issue:
Can't move cursor behind non-editable element (or placeholder) in CKEditor
I used my plugin to insert this block of code into the editor:
<div contenteditable="false">
<img src="someimage.jpg" />
<p>
Some text
<span>Some subtext</span>
</p>
<img src="someStaticImage.jpg" />
</div>
You can also add the display: inline-block; style if you want (see discussion below):
From my tests, it seems like you can't put content before the object using the back arrow, but if you back arrow to that row of content and press the home key, you can type before the object. It also seems that if you click with your mouse in the upper left corner, you can add content before the object.
Both approaches push the object onto the next line because it's a <div>, you can change the style of the div to display: inline-block; if you want the object to stay on the first row. I tried just making the object <div> a <span> instead, but then it becomes possible to edit parts of the object.
You can't use backspace to delete the object, but you can click the object to select it and then delete it.
I checked the info discussed above with Firefox 20 and IE 9 on Win 7. Google Chrome has a bunch of problems:
When the block of HTML is inserted with the plugin, the contenteditable="false" attribute is stripped out.
So I tried to see how it worked if I just pasted that block of code into CkEditor while in source mode. The contenteditable="false" attribute wasn't stripped out, but the whole content area became uneditable.
My tests were using CkEditor 3.6.1, so this may not be a problem in CkEditor 4.X.
This bug report seems to be about the problem I encountered with being unable to do anything in the content area using Chrome, the report indicates version 3.X:
ContentEditable, Image and Chrome
Additional Info
Here's a plugin from CKSource that might be helpful:
Magic Line
The description:
With this plugin you can create new paragraphs into spaces where normally would be impossible to reach. For example, above a table at the beginning of the document.
Here's my plugin that inserts content into the editor, it doesn't solve the problem you have, but you might use it to add functionality to your plugin. I'll write the full instructions in case someone who hasn't created a plugin finds this and wants to give it a try.
Here's the code that goes in the ckeditor/plugins/cwmarinsertsnippet/plugin.js file:
/**
* Plugin to insert the contents of an element into the editor content area.
*/
// Register the plugin with the editor. cwmarinsertsnippet
// http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.plugins.html
CKEDITOR.plugins.add( 'cwmarinsertsnippet',
{
// The plugin initialization logic goes inside this method.
// http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.pluginDefinition.html#init
init: function( editor )
{
// Define an editor command that grabs the content of an element and inserts it into the content area.
// http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.editor.html#addCommand
editor.addCommand( 'cwMarInsertSnippet',
{
// Define a function that will be fired when the command is executed.
// http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.commandDefinition.html#exec
exec : function( editor )
{
// Create an element based on a native DOM element.
var codesnippet = new CKEDITOR.dom.element( document.getElementById( 'resmar' ) );
//alert( codesnippet.getHtml() );
// Insert the element content into the document.
// http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.editor.html#insertHtml
editor.insertHtml( codesnippet.getHtml() );
}
});
// Create a toolbar button that executes the plugin command.
// http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.ui.html#addButton
editor.ui.addButton( 'CwMarInsertSnippet',
{
// Toolbar button tooltip.
label: 'Insert Search Box',
// Reference to the plugin command name.
command: 'cwMarInsertSnippet',
// Button's icon file path.
icon: this.path + 'images/buttonicon.gif'
});
}
});
It needs to be added to the config file with:
config.extraPlugins = 'cwmarinsertsnippet';
and to make the button visible, the button name "CwMarInsertSnippet" needs to be added to the config toolbar entry:
CKEDITOR.config.toolbar_XXXX
[
Snip...
{ name: 'tools', items : [ 'About','CwMarInsertSnippet' ] },
... End Snip
];
The button for the plugin should be 13px X 13px (for CkEditor 3.X, not sure about version 4.X). It gets placed here:
ckeditor/plugins/cwmarinsertsnippet/images
The name should match the one used in the editor.ui.addButton function at the end of the plugin code (this path can really be anywhere you want).
Here's an example of the code to be added to the page where CkEditor is being used:
<div id ="resmar">
<div contenteditable="false">
<img src="someimage.jpg" />
<p>
Some text
<span>Some subtext</span>
</p>
<img src="someStaticImage.jpg" />
</div>
</div>
You can also add the display: inline-block; style if you want:
<div style="display:inline-block" contenteditable="false">
The container element can be hidden with styling if it shouldn't appear on the page.
Basically, just put the content you want to insert inside the element with the target ID
<div id ="resmar">
Content to be inserted.
</div>
Of course the plugin name and the element ID can be anything you like.

Inline Editing But Instance Doesn't Exist

I have my own custom non-jQuery ajax which I use for programming web applications. I recently ran into problems with IE9 using TinyMCE, so am trying to switch to CKeditor
The editable text is being wrapped in a div, like so:
<div id='content'>
<div id='editable' contenteditable='true'>
page of inline text filled with ajax when links throughout the site are clicked
</div>
</div>
When I try to getData on the editable content using the examples in the documentation, I get an error.
I do this:
CKEDITOR.instances.editable.getData();
And get this:
Uncaught TypeError: Cannot call method 'getData' of undefined
So I figure that it doesn't know where the editor is in the dom... I've tried working through all editors to get the editor name, but that doesn't work-- no name appears to be found.
I've tried this:
for(var i in CKEDITOR.instances) {
alert(CKEDITOR.instances[i].name);
}
The alert is just blank-- so there's no name associated with it apparently.
I should also mention, that despite my best efforts, I cannot seem to get the editable text to have a menu appear above it like it does in the Massive Inline Editing Example
Thanks for any assistance you can bring.
Jason Silver
UPDATE:
I'm showing off my lack of knowledge here, but I had never come across "contenteditable='true'" before, so thought that because I was able to type inline, therefore the editor was instantiated somehow... but now I'm wondering if the editor is even being applied to my div.
UPDATE 2:
When the page is loaded and the script is initially called, the div does not exist. The editable div is sent into the DOM using AJAX. #Zee left a comment below that made me wonder if there is some other command that should be called in order to apply the editor to that div, so I created a button in the page with the following onclick as a way to test this approach: (adapted from the ajax example)
var editor,html='';config = {};editor=CKEDITOR.appendTo('editable',config, html );
That gives the following error in Chrome:
> Uncaught TypeError: Cannot call method 'equals' of undefined
> + CKEDITOR.tools.extend.getEditor ckeditor.js:101
> b ckeditor.js:252
> CKEDITOR.appendTo ckeditor.js:257
> onclick www.pediatricjunction.com:410
Am I headed in the right direction? Is there another way to programmatically tell CKEditor to apply the editor to a div?
UPDATE 3:
Thanks to #Reinmar I had something new to try. The most obvious way for me to test to see if this was the solution was to put a button above the content editable div that called CKEDITOR.inlineAll() and inline('editable') respectively:
<input type='button' onclick=\"CKEDITOR.inlineAll();\" value='InlineAll'/>
<input type='button' onclick=\"CKEDITOR.inline('editable');\" value='Inline'/>
<input type='button' onclick=\"var editor = CKEDITOR.inline( document.getElementById( 'editable' ) );\" value='getElementById'/>
This returned the same type of error in Chrome for all three buttons, namely:
Uncaught TypeError: Cannot call method 'equals' of undefined ckeditor.js:101
+ CKEDITOR.tools.extend.getEditor ckeditor.js:101
CKEDITOR.inline ckeditor.js:249
CKEDITOR.inlineAll ckeditor.js:250
onclick
UPDATE 4:
Upon further fiddling, I've tracked down the problem being related to json2007.js, which is a script I use which works with Real Simple History (RSH.js). These scripts have the purpose of tracking ajax history, so as I move forward and back through the browser, the AJAX page views is not lost.
Here's the fiddle page: http://jsfiddle.net/jasonsilver/3CqPv/2/
When you want to initialize inline editor there are two ways:
If element which is editable (has contenteditable attribute) exists when page is loaded CKEditor will automatically initialize an instance for it. Its name will be taken from that element's id or it will be editor<number>. You can find editors initialized automatically on this sample.
If this element is created dynamically, then you need to initialize editor on your own.
E.g. after appending <div id="editor" contenteditable="true">X</div> to the document you should call:
CKEDITOR.inline( 'editor' )
or
CKEDITOR.inlineAll()
See docs and docs.
You can find editor initialized this way on this sample.
The appendTo method has different use. You can initialize themed (not inline) editor inside specified element. This method also accepts data of editor (as 3rd arg), when all other methods (CKEDITOR.inline, CKEDITOR.replace, CKEDITOR.inlineAll) take data from the element they are replacing/using.
Update
I checked that libraries you use together with CKEditor are poorly written and cause errors you mentioned. Remove json2007.js and rsh.js and CKEditor works fine.
OK, so I have tracked down the problem.
The library I was using for tracking Ajax history and remembering commands for the back button, called Real Simple History, was using a script called json2007 which was intrusive and extended native prototypes to the point where things broke.
RSH.js is kind of old, and I wasn't using it to it's full potential anyway, so my final solution was to rewrite the essential code I needed for that, namely, a listener that watched for anchor (hash) changes in the URL, then parsed those changes and resubmitted the ajax command.
var current_hash = window.location.hash;
function check_hash() {
if ( window.location.hash != current_hash ) {
current_hash = window.location.hash;
refreshAjax();
}
}
hashCheck = setInterval( "check_hash()", 50 );
'refreshAjax()' was an existing function anyway, so this is actually a more elegant solution than I was using with Real Simple History.
After stripping out the json2007.js script, everything else just worked, and CKEditor is beautiful.
Thanks so much for your help, #Reinmar... I appreciate your patience and effort.

Prefixing a URL in an window.open function jQuery

I have this HTML:
Track Your Package »
Somebody on this site was able to provide me with a script to prefix the URL with the domain http://www.example.com/ Here's the script:
$(document).ready(function(){
$('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick', $('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick').replace("window.open('", "window.open('http://www.example.com/"));
});
However, I am having a little trouble with this:
The first issue is where there is multiple instances of the element. Here's a fiddle: http://jsfiddle.net/VMmZx/
Instead of one anchor being signed with ID=4 and the other with ID=5 as intended, they're both being signed with ID=4.
The idea is, each window.open function should be prefixed with http://www.example.com however, the remainder of the URL should remain intact...
The second problem I'm encountering is when the element does not exist on a page, the remainder of the jQuery fails...
Here's another fiddle: http://jsfiddle.net/VPf32/
The <a> should get the class foo, but since the element does not exist on the page, the jQuery does not execute.
Since the JavaScript is being included in the HTML template of the ASP.NET server, this can create many problems.
I hope I've been clear and you can help me. Thanks.
You can use .each() to iterate over each matching element and change them individually:
$('a[onclick^="window.open(\'TrackPackage.asp"]').each(function(index, element) {
element = $(element);
element.attr('onclick', element.attr('onclick').replace(/open\('/, 'open(\'http://www.example.com/'));
});​
However, I don't think using links with a href of # and an onclick opening a window is as semantic as it could be. If possible, try changing the markup to this:
Track Your Package »
Now if someone is curious where it will lead them, the browser can show something useful in the status bar when you hover over it.
If you need to adjust the behavior further, add a class and bind for the click event. When they click, prevent the default action and open the window yourself, as you did before.
Why are you doing the click even inline like that? I would just output the links like:
Link Text
And then:
$('a[target=_blank]').click(function(){
var prefix = 'http://domain.com';
window.open(prefix + $(this).attr('href'));
});

Categories

Resources