Tooltipster doesn't work with dynamically generated elements - javascript

I've been dealing with this problem for some days but I can't find the solution. I have a function in Javascript that generates HTML after an Ajax call is done and I call this function like this:
$(document).ready(function() {
$("#list").change(function() {
reloadInfo($('#list').val());
});
reloadInfo($('#list').val());
});
And my function is the next:
function reloadInfo(id) {
var div = document.getElementById(id);
...
code += "<img id='led_" + res.id + "' src='green_led.gif' style='cursor: pointer' class='tooltipstered'>";
code += "<img id='" + res.id + "' src='mygraph.jpg'>";
...
div.innerHTML = code;
}
After that, I've tried to use Tooltipster in order to show 'mygraph.jpg' into a tooltip when I put the mouse over the 'green_led.gif' image and hide it when I move out the mouse cursor. To do so, I've used the next code into my $(document).ready():
$(document).ready(function() {
$("#list").change(function() {
reloadInfo($('#list').val());
});
reloadInfo($('#list').val());
$("body").on('mouseover', '.tooltipstered', function(){
$(this).tooltipster({
trigger: 'custom'
}).tooltipster('open').tooltipster('content', 'MYcontent');
});
});
But it doesn't seem to work. I've read Tooltipster documentation but I don't know what I'm doing wrong when I generate dynamically the HTML code (when I try it with static HTML it works, but I do it a bit different):
JavaScript
$(document).ready(function(){
$(".tooltipstered").tooltipster({
trigger: 'custom',
arrow: false
}).on('mouseover', function() {
$(this).tooltipster('instance').content("foo").open();
}).on('mouseout', function() {
$(this).tooltipster('instance').close();
})
});
HTML
<body>
<button id="1" class="tooltipstered" style="float: right">Hover1</button>
<button id="2" class="tooltipstered">Hover1</button>
</body>
The problem is when I generate HTML with JavaScript. First time I put the cursor over the image I don't get any error in the browser console, but the second time I repeat it i get this errors:
Tooltipster: one or more tooltips are already attached to the element
below. Ignoring.
<img id=​"led_27269" src=​"green_led.gif" style=​"cursor:​ pointer" class=​"tooltipstered">​
Uncaught TypeError: Cannot read property 'width' of undefined
If anybody knows what I'm doing wrong it would be of help. Thank you very much in advanced!!

Two things :
You shall destroy the tooltipsters and recreate them on HTML content change.
Calling a tooltipster method shall be done via $(...).tooltipster(methodName, arg1, arg2,...). Here you should look at the documentation for correct method name and arguments. So, you should call the creation (without method name) each time as you did in $("body").on('mouseover' ....
For recreation :
$(document).ready(function(){
$(".tooltipstered").tooltipster({
trigger: 'custom',
arrow: false
}).on('mouseover', function() {
$(this).tooltipster('instance').content("foo").open();
}).on('mouseout', function() {
$(this).tooltipster('instance').close();
})
});
shall be moved :
function reloadInfo(id) {
$(".tooltipstered").tooltipster('destroy');
... your reloading code
$(".tooltipstered").tooltipster({
trigger: 'custom',
arrow: false
}).on('mouseover', function() {
$(this).tooltipster('instance').content("foo").open();
}).on('mouseout', function() {
$(this).tooltipster('instance').close();
});
}

Related

Get ID of div created by jquery

I have two functions, where the first creates a div in the dom and the second gets the ID via getElementById(). Unfortunately, my second function is just returning null.
I looked in using $.Deffered() in either of my functions, but alas nothing I do seems to work
function one() {
var dynamicDiv = $("<div>").attr("id", 'test');
dynamicDiv.iziModal({
//modal content here
})
}
function two() {
var container = document.getElementById('test');
console.log(container.innerHTML); //not returning any data
}
enter code here
I had hoped to use this with a library that replaces images with a canvas object, but it requires that the "parent element to be a valid DOM Element". I have been searching for a while now, but I can not seem to find anything on the subject that is applicable.
** Edit**
Thank you for pointing out the error in my id (I had tried something else before I pasted). The iziModal function (http://izimodal.marcelodolza.com/) is currently pulling the content in via ajax (which I assume is the problem here):
The iziModal Function:
dynamicDiv.iziModal({
title: '',
autoOpen: 1,
width: 500,
onOpening: function (offer) {
offer.startLoading();
$.get(demoUrl, function (data) {
$('#' + id + " .iziModal-content").html(data);
offer.stopLoading();
});
}
});
Content of the other file:
<div id="test">
<img src="./bundle/images/coupon.jpg" />
</div>
function one() {
var dynamicDiv = $("<div>").attr("id", 'test');
dynamicDiv.iziModal({
//modal content here
});
$("body").append(dynamicDiv);
}

.click + v.split not working together?

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>

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

jquery ui dynamic dialog

I am fairly new to js and jquery. I basically want to be able to change the table and id variables from an onClick event or something appended to the <a> this way I can modify the variables with php later on. This is just proof of concept, and doesnt seem to be working since I made modifications. Is there a way that I can pass variables from the a to the function?
OVERALL GOAL: I want to have an inline onclick that will pass id and table names from loadMe to the function and display table_render.php?id=someid&table=sometable in the dialog box.
<script>
$(function loadMe(table, id) {
$( "#dialog-view" ).dialog({
autoOpen: false,
height: 600,
width: 700,
modal: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
$( "#create-view" ).click(function() {
$( "#dialog-view" ).load("table_render.php?id=" + id + "&table=" + table + "").dialog("open");
});
});
</script>
Some text
<div id="dialog-view" title="">
</div>
You are hooking up the event twice, once via onclick and once via jQuery. You need to pick one.
If you pick the jQuery way (recommended) you're going to get the jQuery arguments (which is just one arg, event). However, jQuery will set this to the element that triggered the event (in this case, your A tag). You can use that to get data off of the A tag.
For instance, if you wanted the ID of the A that got clicked, you could do this in your handler:
var clickedId = $(this).attr('id');
If you want to store some arbitrary info (eg. "tableName") for each A tag, you can either use the HTML 5 data attributes (preferable), or just make up your own attributes (which will work, but is "bad form"). For instance:
<a tableName='testimonials'>
var clickedFoo = $(this).attr('tableName');
or (a little better):
<a data-tableName='5'>
var clickedTableName = $(this).attr('data-tableName');
// Also, I believe this would work:
var clickedTableName = $(this).data('tableName');
* EDIT *
Just to try and clarify a little further, the basic overall idea is this:
1) You write out your A tags to the page, via PHP
1A) As you write them out, you put whatever data is specific to them on the A tag, in the form of an attribute or attributes (eg. id='foo' data-bar='baz').
2) You also write out some Javascript code that says "hey, whenever an A tag gets clicked, run this function"
3) Inside the function that you hooked up to the A tag's click event, you use the this variable (which points to the A tag itself) to get the data (the "variables") that you need
3A) For instance, you could use the JQuery "attr" method: $(this).attr('id')
4) Profit! (or at least do something useful with the data you just got)
so i got it working... heres the solution
function createViewer(id, table) {
var id;
var table;
$("#dialog-view").dialog({
autoOpen: false,
width:650,
minHeight:400,
show:{effect: "fade", duration: 500},
hide:"clip",
resizable: false,
modal: true,
buttons: {
"Close": function () {
$(this).dialog("close");
}
}
});
$("#dialog-view").load("table_render.php?id=" + id + "&table=" + table + "").dialog("open");
};
And the inline code
View Quote
you might want to put $(document).ready()around you functions initialising the dialog and binding the onclick event. Then open the dialog inside the callback of your ajax request.
That way you could dismiss the onclick attribute with the loadFunction, I guess. (tired)
something like:
HTML:
<a href="#" id="trigger" data-my-id="123" data-my-table="myTable">
trigger
</a>
<div id="dialog">
Dialog Contents....
</div>
JS:
$(document).ready(function() {
$("#dialog").dialog({
autoOpen: false,
height: 600,
width: 700,
modal: true,
buttons: {
Cancel: function() {
$(this).dialog("close");
}
}
});
$("#trigger").click(function() {
var id = parseInt( $(this).attr('data-my-id');
var table = $(this).attr('data-my-table');
$("#dialog").load("table_render.php?id=" + id + "&table=" + table + "",
function(){
$("#dialog").dialog("open");
});
});
});​
should do the trick.

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')); });

Categories

Resources