.click + v.split not working together? - javascript

I have a script that converts youtube links to working iframes when loaded automatically, once the user clicks the element with a preloaded thumbnail, it then generates a watchable iFrame. The main part of the code works, but its not wanting to work when told to run after the element is clicked. The code below im trying to get to run removes any content in the 'scr' url containing '&' and after.
The thumbnail element when clicked, loads the iframe: .youtube-box
The iframe called after when clicking .youtube-box:
<iframe class="youtube-frame" src="http://www.youtube.com/embed/qYTT-0A8QIE&list=PLbfa3OWXAjLMk5PKV2KDaRveQt8BntMK5&t=4s&index=13?rel=0;&autoplay=1&vq=hd720" style="height: 622px;"></iframe>
My code:
$(window).on("load", function(){
$(".youtube-box").click(function () {
setTimeout(function(){
jQuery('iframe').attr('src',function(i,v){
return v.split('&')[0]; // get the string part before the `?`
// or
// return v.replace(/\?.*/,'');
});
}, 2000);
});
});
What it is suppose to remove:
&list=PLbfa3OWXAjLMk5PKV2KDaRveQt8BntMK5&t=4s&index=13?rel=0;&autoplay=1&vq=hd720

This is a tempoary fix, but not an absolute solution I found, basically I just added on to the script that turns the element to an iframe
<script>
$(window).on("load", function(){
$(function() {
$('a[href^="https://www.youtube.com/watch"]').each(function() {
var yt_url = this.href,
yt_id = yt_url.split('?v=')[1],
yt_title = $(this).text();
$(this).replaceWith('<div class="youtube-box" style="background-image:url(http://img.youtube.com/vi/' + yt_id + '/0.jpg);"><span class="youtube-title">' + yt_title + '</span><span class="youtube-bar"><span class="yt-bar-left"></span><span class="yt-bar-right"></span></span><span class="youtube-play"></span></div>');
$('div.youtube-box').click(function() {
$(this).replaceWith('<iframe class="youtube-frame" src="http://www.youtube.com/embed/' + yt_id + '?rel=0;&autoplay=1&vq=hd720"></iframe>');
// added to remove youtube playlist from iframe url
jQuery('iframe').attr('src',function(i,v){
return v.split('&l')[0]; // get the string part before the `?`
// or
// return v.replace(/\?.*/,'');
});
});
});
});
});
</script>
Answer to my second question, I put the code right before the code above to fix broken thumbnails:
<script>
$(window).on("load", function(){
jQuery('a').attr('href',function(i,v){
return v.split('&l')[0]; // get the string part before the `?`
// or
// return v.replace(/\?.*/,'');
});
});
</script>

Related

Check if all/multiple iframes are loaded

I am currently trying to run a function when all iframes on the page are loaded. I am using jQuery, but it only works when there is one iframe on the page. Once I start having mutiple iframes my functionality stops working. Here is the code im working with:
$('iframe.preview-iframe').on( 'load', function() {
$('iframe.preview-iframe').contents().find('section[rowposition] a').each(function(){
// Append a span tag with the href of the according content a tag
$(this).append('<span style="position:absolute;left:0;color:red;background:yellow;">' + $(this).attr('href') + '</span>');
});
});
Do I need to write a loop that looks over how many iframes I have and then only run the script once the last iframe is loaded or is there some other way to do it?=
You can do something like the following:
Get all the iframes elements in a variable
Loop through each of the iframes and if all of them are loaded, execute your required code.
$(window).on('load', function() {
var iframes = $('iframe');
var loaded = 0;
iframes.each(function() {
$(this).on('load', function() {
loaded++;
if (loaded == iframes.length) {
// run your code here
$('iframe').each(function() {
$(this).contents().find('section[rowposition] a').each(function() {
// Append a span tag with the href of the according content a tag
$(this).append('<span style="position:absolute;left:0;color:red;background:yellow;">' + $(this).attr('href') + '</span>');
});
});
}
});
});
});

Dynamically Adding HTML into an iFrame - Javascript

I'm attempting to dynamically create an iFrame and add HTML into it from the current document. The iFrame gets created successfully, but when the function gets to the point where it needs to add the HTML in, it doesn't do it.
Here's my code:
function createiFrame(min, max, key) {
console.log("Max-Width", max);
//CREATING A CLASS FOR THE IFRAME
var iframeClass = key + "-" + max;
//var path = window.location.pathname;
//var page = path.split("/").pop();
//ADDING AN IFRAME INTO THE DOCUMENT AND ADDING ON THE CLASS
$(document).ready(function() {
$('<iframe>', {
width: max
}).addClass(iframeClass).prependTo('body');
});
var requiredHTML = document.getElementById('container').innerHTML;
console.log("RequiredHTML", requiredHTML);
//ADDING THE COLLECTED HTML INTO THE IFRAME -- THIS IS WHERE
//IT STOPS WORKING
$('.' + iframeClass).ready(function() {
console.log("iFrame ready");
$('.' + iframeClass).contents().find('body').html("<p>Testing it out</p>");
});
var $head = document.getElementsByTagName('head')[0].innerHTML;
$(document).ready(function() {
$('.' + iframeClass).contents().find('head').append($head);
});
}
EDIT
I've realised this problem is occurring because when I try to run that code, the DOM isn't ready yet.
So new question;
How do I get the DOM ready?
check out this post:
addEventListener to iFrame
you need to use
$('#myIFrame').load(function(){
....
$('.' + iframeClass).ready(function() {
...
}
Doesn't work because an iframe being ready doesn't trigger the Event 'DOMContentLoaded' which .ready() is waiting for. You'll need to refer directly to a document, which will then trigger the DOMContentLoaded event. This should work based on that.
$(iframeClass document).ready(function() {
...
}
I will stress though that this isn't something that I've tried before, but it seems like it's just a matter of which document you're referring to.

pass value/variable from fancybox iframe to parent

I'am trying to pass a variable/ value from the fancybox iframe to the parent window without success.
Fancybox is launched from a link with
class="fancybox fancybox.iframe"
My code in the fancybox.iframe is:
$(document).ready(function(){
$('.insert_single').click(function(){
var test = $('.members_body').find('{row.U_USERNAME}');
setTimeout(function(){ parent.$.fancybox.close();},300);return true;
});
});
Where '{row.U_USERNAME}' is the username to find in the iframe.
Then, in the parent there's the following code:
$(document).ready(function(){
$('.fancybox').fancybox(
{
openEffect:'fade',
openSpeed:500,
afterClose: function(){
alert($(".fancybox-iframe").contents().find(test));
$('#form input[name=username]').val()(test);return false;
}
}
);
});
But when the fancybox is closed, there's no alert showing up with the variable "test", nor the variable is showing up as a value or as a text in the input field of the form.
I've read and tried various solutions found here on stackoverflow without success.
Thanks in advance for helping
EDIT
Here's an Example
When the fancybox is closed the iframe is removed from the document. So you must use beforeClose event instead of afterClose
$(document).ready(function() {
$('a.fancybox').fancybox({
openEffect:'fade',
openSpeed:500,
beforeClose: function() {
// working
var $iframe = $('.fancybox-iframe');
alert($('input', $iframe.contents()).val());
},
afterClose: function() {
// not working
var $iframe = $('.fancybox-iframe');
alert($('input', $iframe.contents()).val());
}
});
});
JSFiddle: http://jsfiddle.net/NXY7Y/1/
EDIT:
I edited your jsfiddle (http://jsfiddle.net/NXY7Y/9/). Update is in this link
http://jsfiddle.net/NXY7Y/13/
Main page javscript:
$(document).ready(function() {
$('a.fancybox').fancybox({
openEffect:'fade',
openSpeed:500//,
//beforeClose: function() {
// // working
// var $iframe = $('.fancybox-iframe');
// alert($('input', $iframe.contents()).val());
//},
//afterClose: function() {
// // not working
// var $iframe = $('.fancybox-iframe');
// alert($('input', $iframe.contents()).val());
//}
});
});
function setSelectedUser(userText) {
$('#username').val(userText);
}
No need to use afterClose or beforeClose events. Just access the parent function setSelectedUser from the iframe on link click event like this:
$(document).ready(function() {
$('a.insert_single').click(function() {
parent.setSelectedUser($(this).text());
parent.$.fancybox.close();
});
});
Some clarifications :
You should use .find() to find elements by selector (you are trying to find a variable .find(test), which is not a valid format).
You should use .val() to get the contents of an input field or .val(new_value) to set the contents of an input field
You should use .html() or .text() to get the contents of any element other than input,
example: having this html code
<p class="test">hola</p>
... and this jQuery code
var temp = $(".test").html();
... temp will return hola.
On the other hand, if you have control over the iframed page and it's under the same domain than the parent page, then you may not need to set any jQuery in the child page.
so, having this html in the child (iframed) page for instance
<div class="members_body">
<p>GOOGLE</p>
<p>JSFIDDLE</p>
<p>STACKOVERFLOW</p>
</div>
You could set this jQuery in your parent page to get the contents of any clicked element in your child page :
var _tmpvar; // the var to use through the callbacks
jQuery(document).ready(function ($) {
$(".fancybox").fancybox({
type: "iframe",
afterShow: function () {
var $iframe = $('.fancybox-iframe');
$iframe.contents().find(".members_body p").each(function (i) {
$(this).on("click", function () {
_tmpvar = $('.members_body p:eq(' + i + ')', $iframe.contents()).html();
$.fancybox.close();
}); // on click
}); // each
},
afterClose: function () {
$('#form input[name=username]').val(_tmpvar);
}
});
}); // ready
Notice that we declared the var _tmpvar globally so we can use it within different callbacks.
See JSFIDDLE

Change a href=# to javascript:

Hi I asked before on how to load a div's content (A url) by clicking a button and not on page load before and I got this code as an answer:
<script type="text/javascript">
function toggleDiv(id){
if ($('#' + id).html() == '') {
$.ajax({
url: 'api.microsofttranslator.com/V2/Ajax.svc/Translate?appId=SOMETHING&from=en&to=de&text=Hello', // your url to microsoft translator
success: function(data) {
$('#' + id).html(data);
},
error: function() {
$('#' + id).html('The resource could not be loaded');
}
});
}
$('#' + id).toggle(); // Toggle div visibility
}
</script>
Show/Hide Value
<div id="a" style="display:none"></div>
First of all it doesn't work correctly and always show "The resource could not be loaded" if you put a txt link like (http://knowpersia.com/a.txt) it doesn't work either.
Secondly the Show/Hide Value link uses a href=# and onclick system to work. When I use it on my website it gets back to the homepage when I click it. Is there a way to change it to something like:
Show/Hide Value
Thanks
You have to pass an id to the toggleDiv() function, and you're passing a collection of objects -> toggleDiv('a') // Nop.
Also, if you're using jQuery, I suggest you get rid of that ugly inline code. Then, you can pass jQuery objects into your function:
Show/Hide Value
<div id="content"></div>
.
var toggleDiv = function($el) {
if ($el.empty()) { // You can just use `empty()`
$.ajax({
url : 'api.microsofttranslator.com/V2/Ajax.svc/Translate?appId=SOMETHING&from=en&to=de&text=Hello', // your url to microsoft translator
success : function (data) {
$el.html(data);
},
error : function () {
$el.html('The resource could not be loaded');
}
});
}
$el.toggle(); // Toggle div visibility
};
$('#link').click(function(){ toggleDiv($('#content')); });

How do you get a return value from a colorbox?

I have a colorbox that lets the user select an image. How do I get the file name back from the colorbox? (I have noticed the onClosed function.)
Solution:
As #Gummy sugested i used the onComplete function as the following code exemplifies:
'Return' page:
<input id="colorbox_hidden_return" type="hidden"/>
...
$("#whatever-you-want-to-click-on-to-get-the-color-box").click(function() {
$.colorbox(
{
href: '<?= site_url('the-source-url') . '/' ?>' + id,
height: "600px;",
onClosed: function() { // called when the colorbox closes
var image = $('#colorbox_return_hidden').val();
// ... other processing - what ever the value was is in image
}
});
});
In the colorbox source
var image_name_var = "dynamicaly_change_this_name.png";
$('#submit-or-use-button-id').click(function() {
$('#colorbox_return_hidden').val(image_name_var);
});
Any time while colorbox is open, you can call the element method to retrieve a jQuery object of the current element. From there you can select the element, and access the href property:
href = $.colorbox.element()[0].href;
Also, in any callback the execution context (the value of 'this') will be the current element. So if you wanted to use the onComplete callback for example, you could do something like this:
$('#example').colorbox({onComplete:function(){
href = this.href;
}});
This might do it for you
$(document).bind("cbox_complete", function(){
var href = $.colorbox.element().attr("href");
//do something else
});

Categories

Resources