CKEditor - Change image source - javascript

I have made some custom functionality to the CKEditor. In short, it shows a div tag with 5 links, for Small, Medium, Large X-Large and Original size.
When I click the links, it changes the SRC attribute of the image to the correct size.
It works, but it doesn't persist back to the editor. It's like the Image i get through the click event target, is not part of the Source code.
How can I change the Source code, when manipulating with the elements in the editor?
My code looks like this:
$(target).ckeditor(function (editor) {
$(this.document.$).bind("click", function (event) {
var target = $(event.target);
if (target.is("img")) {
var p = $("<div contenteditable='false' class='image-properties'>" + Milkshake.Resources.Text.size + ": <a class='sizeLink' href='#size1Img'>S</a> <a class='sizeLink' href='#size2Img'>M</a> <a class='sizeLink' href='#size3Img'>L</a> <a class='sizeLink' href='#size4Img'>XL</a> <a class='sizeLink' href='#size5Img'>Org.</a></div>");
p.css("top", target.position().top);
var regex = new RegExp(/(size\d{1}img)/i);
var match = regex.exec(target.attr("src"));
if (match != null) {
var imgSrize = match[0];
p.find("a[href=#" + imgSrize + "]").addClass("selected");
}
p.delegate("a", "click", function (e) {
var link = $(e.target);
if (!link.is(".selected")) {
$(".selected", link.parent()).removeClass("selected");
link.addClass("selected");
var imageSrc = target.attr("src");
imageSrc = imageSrc.replace(/(size\d{1}img)/i, link.attr("href").substring(1));
target.attr("src", imageSrc);
target.css("width", "");
target.css("height", "");
}
e.preventDefault();
});
p.insertAfter(target);
} else if (!target.is("div.image-properties")) {
$("div.image-properties", target.parent()).remove();
}
});

The src of images and href of links are protected in CKEditor to avoid browser bugs (when copying, dragging or sometimes even just loading the content), so you must update also this custom attribute:
data-cke-saved-src

Related

Replace a hyperlink with an iframe

I am trying to replace internal links:
<div class="activityinstance">
activity
</div>
to become:
<div class="activityinstance">
<iframe src="http://website.com/hvp/view.php?id=515512">
activity
</iframe>
</div>
I have been able to replace just the text with an iframe using jquery.
https://codepen.io/alanpt/pen/mWJvoB
But this is proving to be quite hard.
Another difficulty is that it needs to only be links with hvp in the address.
I appreciate any help - thanks.
$('body').ready(function(){
$('.activityinstance a').each(function(){ // get all the links inside the .activeinstance elements
var $this = $(this); // ...
var $parent = $this.parent(); // get the parent of the link
var href = $this.attr('href'); // get the href of the link
if(href.indexOf('/hvp/') == -1) return; // if the href doesn't contain '/hvp/' then skip the rest of this function (where the replacement happens)
$this.remove(); // remove the link as I don't see any reasong for it to be inside the iframe
$parent.append('<iframe src="' + href + '"></iframe>'); // add an iframe with the src set to the href to the parent of the link
});
});
A sample of:
<div class="activityinstance">
activity
</div>
[Because of a fact that having HTML inside of an IFRAME tags has no bearing, and is a complete waste of bytes, we will leave it out. And because this solution doesn't need wrappers, we'll stick to the good old (plain and clean) JavaScript].
The snippet:
[].slice.call(document.links).
forEach(
function( a ) {
if( a.href.match(/hvp/) ) {
a.outerHTML = "<iframe src=" + a.href + "><\/iframe>"
}
} );
will result in clean HTML such as:
<div class="activityinstance">
<iframe src="http://website.com/hvp/view.php?id=515512"></iframe>
</div>
...of course, without indentations and unnecessary white-spaces.
$('a').replaceWith(function () {
var content = this;
return $('<iframe src="about:blank;">').one('load', function () {
$(this).contents().find('body').append(content);
});
});

can i identify a link that have an imag with certain href

I am working on a web application, and i need to adjust a People Picker dialog height. currently to keep firing the script when the user open/close the dialog , i set a timer (2 seconds for the script to run), as follow:-
var interval = null; //Defines the start interval variable
$(document).ready(function () { // jQuery needed for this
/* People Picker Fix Starts */
if (navigator.appVersion.indexOf("MSIE 10") > -1) { // IE 10 Specific condition for People Picker Bug
interval = setInterval(adjustPeoplePicker, 2000);
}
/* People Picker Fix Ends */
});
function adjustPeoplePicker() {
if ($('.ms-dlgFrame').contents().find('#resultcontent').length > 0) {
$('.ms-dlgFrame').contents().find('#resultcontent').css('height', '350px');
$('.ms-dlgFrame').contents().find('#MetadataTreeControlTreeSearch').css('height', '350px');
//clearInterval(interval);
}
}
here is the realted markup for the dialog to open:-
<a id="ctl00_ctl41_g_a4fb58d0_ad0d_40cf_a4a3_ccabea410e43_ff141_ctl00_ctl00_UserField_browse" href="javascript:" onclick="__Dialog__ctl00_ctl41_g_a4fb58d0_ad0d_40cf_a4a3_ccabea410e43_ff141_ctl00_ctl00_UserField(); return false;" title="Browse">
<img alt="Browse" src="/_layouts/15/images/addressbook.gif" title="Browse">
</a>
so my question if i can fire the script only when the user click on <a> that have an <imag> inside it where the imag src = addressbook.gif , instead of keeps firing the script every 2 seconds??
$('a img').on('click', callScriptForImage);
....
// it is executed every time, but will call function adjustPeoplePicker()
// only if src attribute includes addressbook.gif, as you asked
function callScriptForImage(e){
var src = $(this).attr('src');
// read image src attribute
if( /addressbook\.gif/.test(src)){
// if src attribute includes addressbook.gif, call function
adjustPeoplePicker();
}
}
You could also listen for clicks on image that have that src attribute, with:
$('a img[src$="addressbook.gif"]').on('click', adjustPeoplePicker);
This way it is a lot cleaner.
<html>
<head>
<script>
function setClick(){
var tL = document.querySelectorAll("img[src*='addressbook.gif']"); //Getting all images which src contains addressbook.gif
for(var i=0, j=tL.length;i<j; i++){
//Just to visualize
tL[i].style.outline = '1px solid red';
//We actually click on the parent (a) and not the img so we set the click on the a tag
//The other tags will keep your normal onclick settings.
tL[i].parentNode.onclick = function(){
//Put your special script for those cases.
//adjustPeoplePicker() //Some version of this.
return false
}
}
}
</script>
</head>
<body onload = 'setClick()'>
<a href = 'https://www.google.com'><img alt = 'Browse' src = 'https://www.google.com/images/srpr/logo11w.png' /></a>
<a href = 'https://www.google.com'><img alt = 'Browse' src = 'https://www.google.com/images/srpr/logo11w.png?test=addressbook.gif' /></a>
<a href = 'https://www.google.com'><img alt = 'Browse' src = 'https://www.google.com/images/srpr/logo11w.png' /></a>
</body>
</html>
https://jsfiddle.net/7u3m2cng/1/
I am assuming you're asking to check to see whether the <img> src = addressbook.gif and NOT the href of <a>?
If that is the case, this should work for you:
$('a img').on('click', function () {
//Check to see if if the href matches addressbook.gif
var src = $(this).attr('src');
var regex = /addressbook\.gif/i;
if (regex.test(src)) {
// Execute your code here.
} else {
//Put anything else you want here
}
});
Hope this helps!
JRad The Bad

Impliment the animation on click only at the first click?

I have multiple anchor tags with a rel="<img src"#"/>".
When I click on any <a></a>, I show a large image in another div with the rel value using a fadeIn effect.
What I want to do is check if the large image has the same src as the rel of the anchor and prevent the fadeIn effect if so.
$(document).ready(function () {
$("a.largeimg").click(function () {
var image = $(this).attr("rel");
$('.main-product-image').html('<img src="' + image + '"/>');
$('.main-product-image img').hide();
$('.main-product-image img').fadeIn();
return false;
if(src == image) {
$('.main-product-image img').show();
}
});
You can check if the rel of the anchor and the src of the image are the same and if so escape the function before the fade in code, like so:
var src = $('.main-product-image img').attr("src");
if (src == image) return false;
If I understand you question correctly, before the animation you need to confirm if the src of the image is equal to the rel attribute of the clicked element, thus preventing the animation!
JQUERY
$(document).ready(function () {
// use bind when targeting many elements
$("a.largeimg").bind("click", function () {
var $target = $('.main-product-image'), // target element
src = $target.find('img').attr("src"), // src from existent image
image = $(this).attr("rel"); // rel from clicked element
// if src different from image
if (src != image) {
$target.html('<img src="' + image + '"/>'); // append new image
$target.find('img').hide().fadeIn(); // perform the animation
}
// prevent the browser from continuing to bubble the clicked element
return false;
});
});
Ps:
Not tested, but should work just fine!

Changing JS code from clicking image to clicking link

I found the following JS online, which functions like:
If an image is clicked, open the image in new window and prompt for print. Once printed the window closes. I need this script modified to click a print link it prints an image then closes the new image window. So I want to change from clicking the image itself to clicking a link that says print image.
Here is the code:
<script type="text/javascript">
/* <![CDATA[ */
function makepage(src)
{
// We break the closing script tag in half to prevent
// the HTML parser from seeing it as a part of
// the *main* page.
return "<html>\n" +
"<head>\n" +
"<title>Temporary Printing Window</title>\n" +
"<script>\n" +
"function step1() {\n" +
" setTimeout('step2()', 10);\n" +
"}\n" +
"function step2() {\n" +
" window.print();\n" +
" window.close();\n" +
"}\n" +
"</scr" + "ipt>\n" +
"</head>\n" +
"<body onLoad='step1()'>\n" +
"<img src='" + src + "'/>\n" +
"</body>\n" +
"</html>\n";
}
function printme(evt)
{
if (!evt) {
// Old IE
evt = window.event;
}
var image = evt.target;
if (!image) {
// Old IE
image = window.event.srcElement;
}
src = image.src;
link = "about:blank";
var pw = window.open(link, "_new");
pw.document.open();
pw.document.write(makepage(src));
pw.document.close();
}
/* ]]> */
</script>
<img src="fortune.jpg" onclick="printme(event)" />
I do not know any JS so I apologize. I only do php/mysql.
Best Regards!
Jim.
<img src="someurl.jpg" id="imgid' />
Print the image
function printme(id)
{
var src = document.getElementById(id).src;
var link = "about:blank";
var pw = window.open(link, "_new");
pw.document.open();
pw.document.write(makepage(src));
pw.document.close();
}
In the old method, the printme function knows what image should be printed: the same image that was clicked; when you change the trigger, you need to tell the function explicitly what image you want to print. That is why we are adding an id to the image and pass it to printme function. But if you only have one image on the page, or if a spacial relation exists (like the link always being the immediate next node after the image), then we can do it differently and need no id.
I don't know what your link looks like, but assuming it's just a plain anchor:
Change from:
<img src="fortune.jpg" onclick="printme(event)" />
To:
<img id="printableImage" src="fortune.jpg" onclick="printme(event)" />
<a href="javascript:void(0);" onclick="printme('printableImage')" />
Then alter the printme() function to retrieve the image src from the passed in image element id (jQuery makes this easy):
function printme(printableImageId)
{
var src = $('#' + printableImageId).attr('src');
// the rest of the logic...
}
You'll need to modify the printMe function a bit, doing this should fix it:
function printme(evt)
{
if (!evt) {
// Old IE
evt = window.event;
}
var anchor = evt.target;
if (!anchor) {
// Old IE
anchor = window.event.srcElement;
}
src = anchor.href;
link = "about:blank";
var pw = window.open(link, "_new");
pw.document.open();
pw.document.write(makepage(src));
pw.document.close();
return false;
}
And then on your actual anchor you would do the following:
Print

jquery get rel attribute and change it

Hey guys, I have the following code. It is basically a gallery script and when I mouse over the thumbnail, it will change the a bigger version of the thumbnail:
$.fn.CloudZoom = function (options) {
try {
document.execCommand("BackgroundImageCache", false, true);
} catch (e) {}
this.each(function () {
var relOpts, opts;
eval('var a = {' + $(this).attr('rel') + '}');
relOpts = a;
if ($(this).is('.image')) {
$(this).css({
'position': 'relative',
'display': 'block'
});
$('img', $(this)).css({
'display': 'block'
});
if ($(this).parent().attr('id') != 'imageBox') {
$(this).wrap('<div id="imageBox"></div>');
}
opts = $.extend({}, $.fn.CloudZoom.defaults, options);
opts = $.extend({}, opts, relOpts);
$(this).data('zoom', new CloudZoom($(this), opts));
} else if ($(this).is('.thumbs')) {
opts = $.extend({}, relOpts, options);
$(this).data('relOpts', opts);
$(this).bind('mouseenter click', $(this), function (event) {
var data = event.data.data('relOpts');
$('#' + 'mainImage').data('zoom').destroy();
$('#' + 'mainImage').attr('href', event.data.attr('href'));
// Change the small image to point to the new small image.
$('#' + 'mainImage' + ' img').attr('src', data.thumby);
$('#' + 'mainImage').CloudZoom();
return false;
});
}
});
return this;
};
The html reads as follows:
<li>
<a href="gfx/boss_black.jpg" class="thumbs" rel="thumby:'gfx/boss_black.jpg'">
<img src="gfx/boss-black-small.jpg">
</a>
</li>
What I want to do is to write the rel="" tag without the "thumby".
I want the rel tag look like this:
rel="gfx/boss_black.jpg"
When I do this, the JS doesn't work anymore. How do I change the JS to simply get the "rel"?
var img = $('#' + 'mainImage' + ' img'),
rel = img.parent().attr('rel'),
thumby = rel.substr(8, rel.length - 9);
img.attr('src', thumby);
I would recommend storing the alternative src attribute in an attribute other than rel though. A HTML5 data attribute would be a good candidate.
Also, that is a bizarre selector :)
If I understand correctly - there is a library called thumby that requires a special format for your rel tag that you do not want in your source.
I can see two possible soultions.
Try to execute the javascript that changes the rel tag before the thumby library is included. Javascript loads and executes in the order specified in your HTML document. Hopefully thumby will pick up the changed value, but the source html contains the old value.
Modify the thumby library - specifically the part that reads from rel, and maybe make it identify where to operate based on the class thumbs instead.
Something like:
<li>
<a href="gfx/boss_black.jpg" class="thumbs">
<img src="gfx/boss-black-small.jpg" rel="gfx/boss_black.jpg">
</a>
</li>
...
$('.thumbs img').hover(
function () {
var r = $(this).attr('rel'), a = $(this).attr('src');
$(this).attr({'rel':a,'src':r});
},
function () {
var r = $(this).attr('rel'), a = $(this).attr('src');
$(this).attr({'rel':a,'src':r});
}
);

Categories