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);
});
});
Related
I'm new to jQuery and JS. How can I rewrite these functions correctly using jQuery? I know it's standard JS which was working fine with the manual HTML markup but I now also need to go through page and find iframes with YouTube src and take ID and then recreate them with the first example markup.
I'm totally stuck. I think I have it more or less, but not sure where to go to now.
Fiddle: https://jsfiddle.net/yurt5bb6/
First example uses my markup:
<div class="video-container">
<div class="video-player" data-id="Cv_2mp3X868"></div>
</div>
Which works as I need, however I think now I need to foreach on load and create that same markup from iframe embeds the functions should be better.
Attempt:
function createThumb(id) {
return '<img class="youtube-thumb" src="//i.ytimg.com/vi/' + id + '/hqdefault.jpg"><div class="play-button"></div>';
}
function createIframe() {
var iframe = $("iframe");
iframe.attr("src", "//www.youtube.com/embed/" + this.parentNode.dataset.id + "?autoplay=1&autohide=2&border=0&wmode=opaque&enablejsapi=1&controls=0&showinfo=0");
iframe.attr("frameborder", "0");
iframe.attr("id", "youtube-iframe");
this.parentNode.replaceChild(iframe, this);
}
$(document).ready(function() {
// build video from default markup
var defaultVideo = $(".video-player");
$(defaultVideo).each(function (index, value){
var p = $('<div></div>');
p.innerHTML = createThumb(v[n].dataset.id);
p.onclick = createIframe;
v[n].appendChild(p);
});
// search for social embeds and recreate to our markup
$('iframe[src*="youtube.com"]').each(function() {
var loadedVideoURL = $('iframe').attr('src').match(/[^/]*$/)[0];
console.log(loadedVideoURL);
});
});
I've tried to clean up the messy mix of native JS and jQuery and made some edits to your fiddle: https://jsfiddle.net/yurt5bb6/2/
Default function:
(function() {
$.each($('.video-player'), function() {
$(this).append(videoThumb($(this).data('id')));
$(this).on('click', videoIframe);
});
$.each($('iframe'), function() {
// Rebuild the given template
var player = $('<div class="video-player">');
// Strip youtube video id for data-id attribute
var id = $(this).attr('src');
id = id.substr(id.lastIndexOf("/")+1);
player.attr('data-id', id);
player.html(videoThumb(id));
player.on('click', videoIframe);
var videoContainer = $('<div class="video-container">');
videoContainer.append(player);
$(this).replaceWith(videoContainer);
});
})();
Iframe render function:
function videoIframe() {
var iframe = $('<iframe>');
iframe.attr("src", "//www.youtube.com/embed/" + $(this).attr('data-id') + "?autoplay=1&autohide=2&border=0&wmode=opaque&enablejsapi=1&controls=0&showinfo=0");
iframe.attr("frameborder", "0");
iframe.addClass("youtube-iframe");
$(this).empty();
$(this).append(iframe);
}
Also changed the CSS, made a class instead of id for youtube-iframe.
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
I am having an iframe inside a div element which is hidden/display none, I want to get the href attribute of a tag using javascript my code is
HTML
<div id="questions" style="display: none;">
<iframe id="article_frame" width="100%" height="100%">
Click here
</iframe>
</div>
JS
window.onload = function() {
alert("Hello " + window.document.getElementById("article_frame"));
}
But I am getting alert as "Hello null" any solution
Thanks
Thanks All,
I have got the answer with javascript it just simple code
var anchor = document.getElementById('en_article_link').firstChild;
var newLink = anchor.getAttribute("href")+"sid="+sidvalue;
anchor.setAttribute("href", newLink);
Ok i feel this may be a slight overkill but it will get you what you require (the href value of the anchor tag inside the iframe) :
window.onload = function() {
var frame = window.document.getElementById("article_frame");
var myString = frame.childNodes[0].textContent
, parser = new DOMParser()
, doc = parser.parseFromString(myString, "text/xml");
var hrefValue = doc.firstChild.getAttribute('href');
alert("Hello " + hrefValue);
}
I guess it depends on your requirements but another way would be to create a string and then using functions: substring and indexof you could get your value. Here is how you would get the string:
window.onload = function() {
var frame = window.document.getElementById("article_frame");
var elementString = frame.childNodes[0].textContent;
//then perform your functions on the string here
}
Note that you can only access the contents of an iframe that contains a page on the same domain due to the Same-Origin Policy (Wikipedia).
I recommend using jQuery for this. The tricks here are:
Wait for the iframe to finish loading $("#article_frame").ready()
Access the iframe's document $("#article_frame").contents()
From there you're just handling the task at hand:
$("#article_frame").ready(function() {
alert("Hello " + $("#article_frame").contents().find("#en_link").href);
});
I have an img html block <img src="folder1/folder2/folder3/logo1.png"> positioned inside a big div like this
<div id="editorial">
<div id="img_editorial"><img src="folder1/folder2/folder3/logo1.png" /></div>
</div>
When user hovers the <div id="editorial"> (mouseover) i want to read the attribute of <img> which is folder1/folder2/folder3/logo1.png extract the logo1.png from this and add on_ to the logo ( on_logo1.png ) and then output it with jquery .html() function to overwritte <div id="img_editorial">
On mouseout i want to return to logo1.png ... because i have multiple background changes in that parent div ... so the basic functionality is to grayout a logo when mouse is over a big div (also div`s background changes ... etc) ...
So .. how can i read the <img> attribute and then extract logo1.png and not the whole folder1/folder2/folder3/logo1.png ...
You can read the attribute like this:
var img_src = $('#img_editorial img').attr('src');
This will give you:
folder1/folder2/folder3/logo1.png
Than you can split it with:
var split_img_src = img_src.split('/');
This will give you an array, something like:
split_img_src[0] = folder1;
split_img_src[1] = folder2;
split_img_src[2] = folder3;
split_img_src[3] = logo1.png;
so the last value in the array should always be the name of the file - no matter how long the directory tree is.
So you now have the file name, you can append what ever you want to it and do what ever you need.
Good luck.
Here! just a nice solution:
$('#img_editorial img').hover(function(){
imgSrc = $(this).attr('src');
var imgSplit = imgSrc.split('/');
var imgName = imgSplit[3];
$(this).attr('src', imgSrc.replace(imgName, 'on_'+imgName) );
},function(){
$(this).attr('src', imgSrc);
});
If you want, open Firebug and play with this DEMO
The following should do what you want. It just stores the original image using the jQuery .data() API and puts it back when on .mouseleave() of the <div>.
$('div#editorial').mouseenter(function() {
var originalSrc = $('img', this).prop('src');
$(this).data('originalSrc', originalSrc);
var pathComponents = originalSrc.split('/');
var logo = pathComponents.pop();
pathComponents.push('on_' + logo);
$('img', this).prop('src', pathComponents.join('/'));
}).mouseleave(function() {
$('img', this).prop('src', $(this).data('originalSrc'));
});
The demo sort of works but I have no _on image so it just 404s. I hope you get the idea :-)
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