New to posting on stackoverflow here, so my apologies in advance if I messed anything up here.
I'm using Twitter Bootstrap's popovers. My popovers seem to be working for elements that I manually type into my HTML document - but NOT the elements that I dynamically generate via Javascript / Ajax.
For example, the popover seems to work if I manually add this directly to my HTML document:
<p rel=popover data-content='It is so simple to create a tooltop for my website!' data-original-title='Twitter Bootstrap Popover'>hover for popover</p>
But what I really need is for my dynamically generated elements to have popovers. I use an XMLHttpRequest to send a request to a PHP file, and then grab the responseText and display it. When I add this line of code to my aforementioned PHP file:
echo "<p rel=popover data-content='It is so simple to create a tooltop for my website!' data-original-title='Twitter Bootstrap Popover'>hover for popover</p>";
... surely enough, the words "hover for popover" appear - but the popover itself doesn't work!
This has been driving me nuts for some time and it would be incredible if someone could lend me a helping hand! I've also added the JQuery function I'm using to enable Bootstrap's popovers below, for what that's worth.
$(function (){
$("[rel=popover]").popover({placement:'left'});
});
I've done a thorough search of similar problems and the best I could find was this link. But that link doesn't seem to have any solutions either. Thanks in advance again!
UPDATE:
Fixed! Many thanks to everyone who helped out. My problem was that the function was being called BEFORE the elements were added into the Document Object Model. There are multiple possible fixes - I simply tested out the solution by shifting the popover function to the END of the Ajax function and it worked!
You need to call $("[rel=popover]").popover({placement:'left'}); AFTER the elements are in the DOM.
UPDATE
If you are using jQuery
$(element_selector)
// load results into HTML of element_selector
.load('your/php/file')
// when done, initialize popovers
.done(function(){
$("[rel=popover]").popover({placement:'left'});
});
OR a catch all for jQuery ajax requests
$.ajaxComplete(function(){
$("[rel=popover]").popover({placement:'left'});
});
In the success function of the ajax you need to call the popover. Something like this
success:function(){
$("[rel=popover]").popover({placement:'left'});
}
This Function will work properly in the selector you have to specify the location on the page where you have to search "rel=popover" like I put *
$(function ()
{
console.info($("*[rel=popover]"));
$("*[rel=popover]").popover();
});
Related
So I am making a website for radio streams and was told I should use Jquery and AJAX to load the HTML files into a div on button click so that I wouldn't have to make the user load a completely new HTML page for each radio stream. But I am a bit lost since I am new to this language and I am not entirely sure what I am doing wrong.
Currently I have a index.html page that loads each individual div and loads all the available radio stations in an iframe linking to an HTML file. In this HTML file there are around 40 buttons that each have to link to their own radio stream. On a button press I want said stream to load into the 'radio player' div for a smooth transition.
After trying to google the problem I was told to do this with the following JavaScript code:
$(function(){
$(".538").click(function(){
$("#div3").load("/includes/about-info.html");
});
});
Since each button is also showing its own image file, I tried to add class="538 to each image source so the JavaScript knows what is targeted. Unfortunately it doesn't seem to work at all and I have no clue what to do. I tried to do this in a separate index.js file which unfortunately didn't work, so I tried to use the JavaScript code in the HTML file itself, and this didn't seem to do the trick either.
TL/DR: trying to load HTML code in a div when an image button is clicked.
Is there perhaps a tutorial for this available? I tried to search the web but couldn't find anything at all. If anyone is able to help me out with this problem I'd love you forever.
I think what's happening is that you're working with dynamic elements. More importantly you should never use numbers to start off either a class name or id.
Unless you post a bit more code it's hard to figure out exactly what you're wanting to do.
If you work with dynamic html the click event won't work, because well you need do dynamically bind the event listener.
For that you can use
$('#dynamicElement').on('click', function() {
$(this).find('#elementYouWantToLoadInto').load('/includes/about-info.html');
});
The above code works if the element is nested in the button. If it's an external element then use.
$('#dynamicElement').on('click',function() {
$('#elementYouWantToLoadInto').load('/includes/abount-info.html');
});
You mentioned that this language is a bit new to you; If you're open to a bit of refactoring:
Your main page should have 2 sections:
<div id='myButtons'>
<input type='radio' data-url='/includes/about-info.html' />
<...>
</div>
<div id='myContent'></div>
<script>
$(function() { //jquery syntax - waits for the page to load before running
$('#myButtons').on('click', 'input', function() { // jquery: any click from an input inside of myButtons will be caught)
var button = $(this),
url = button.data('url'),
content = $('#myContent');
content.load(url);
});
</script>
Jquery: http://api.jquery.com/
you can try this
$('#myButtons').on('click', 'input', function() {
$.get("about-info.html", function(data) {
$("#div3").html(data);
});
});
or
$(document).ready(function(){
$(function(){
$(".radio538").click(function(){
$("#div3").load("/includes/about-info.html");
});
});
})
$(document).ready(function(){
$('#radio1').on('click',function(){
#('#loadradiohere').load('/includes/about-info.html');
});
});
Try that code in your .js file. I am still working for a similar project man.
So I have a website I am working on just as a personal website that uses jQuery and jQuery UI
Previously I have been using hidden html code and just using jquery to show it.
But its making my html file messy so I wanted to use jquery's .load() to do the same thing but from an external file.
Right now, its set to a .click function.
For my hidden html it shows it every time when I click a particular element.When you click on a different element it. It hides the first one. I am doing it by having a div with 2 classes. The problem is when I tried to load html into a hidden div, and then show it and hide it, it only worked the first time.
Enough talk, here is my code. #1 works , #2 only works on the first click. And leaves imagearea blank every time after.
$(".jquery").click(function(){
clearImageArea();
hideThumbnails(5);
showThumbnails();
$("#1").click(function(){
$(".imagearea").html(js);
$(".jscode").show(1000);
$(".title").text("Extending jQuery");
});
$("#2").click(function(){
$(".jquery2").empty();
$(".jquery2").load("jqueryEx.html");
var jquery2 = $(".jquery2");
$(".imagearea").html(jquery2);
$(".jquery2").show(1000);
$(".title").text("Extending Jquery Example");
});
});
now my hidden stuff in my html file
First my html and js code is loaded into here from jqueryEx.html and is being hidden elsewhere in my javascript via $(".hidden").hide(); and loaded then into into imagearea via .html() and shown via .show()
<div class="jquery2 hidden">
</div>
My other div looks like this which is put into imagearea by clicking on #1
<div class="jscode hidden">
<div class="block">
//lots of js code escaped out into html
</div> <!-- end of block-->
</div>
elsewhere in my JS code at the beginning I have var js=$(".jscode"); to load it into the js variable you saw earlier.
if you want to see an out of date example of what I am working on
go to www.3realsoft.com (only cs and js work on skills)
if you want to see any additional parts of my code, just ask. Most of it is there on my website though.
I got to this item in my search results, when I was trying to have a button both load and refresh the content, and the load was working but the refresh was not working.
Here's a shorter version of the solution, setting Cache to false was the key. Solution found over at this other link, but I'm posting this concept here because if Google dropped me in this item, others looking for the same will also probably find themselves here. Props to John Millikin, make sure to go over to his answer and upvote him: Stop jQuery .load response from being cached
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});
$('.detail-expand').click(function () {
var detailRowElement = $(this).closest('.session-row-tr').next();
var detailElement = detailRowElement.find('.detail-row-div');
var sessionId = detailElement.data("sessionId");
detailElement.empty();
detailElement.load('/Admin/WebLogPartial/' + sessionId, function () {
$.bootstrapSortable(true, 'reversed');
});
detailRowElement.show();
});
});
</script>
Anything that depends on the HTML being loaded must be done in the callback function, because the first A in AJAX stands for asynchronous.
$("#2").click(function(){
$(".jquery2").empty();
$(".jquery2").load("jqueryEx.html", function() {
var jquery2 = $(".jquery2");
$(".imagearea").html(jquery2);
$(".jquery2").show(1000);
$(".title").text("Extending Jquery Example");
});
});
I'm not really sure what you're trying to do with .html(jquery2), since the argument to .html() is supposed to be a string, not a jQuery object. Maybe you meant:
var jquery2 = $(".jquery2").html();
I am trying to understand the difference between JQuery and JavaScript.
And apologies if this is a silly question.
This is my attempt at JQuery. On pressing the button the text in <p> should change as requested. I cannot get this to work.
http://jsfiddle.net/QaHda/7/
this is my JavaScript attempt. I cannot get this to work either
http://jsfiddle.net/aLhb8/1/
Can someone please help me with
my jQuery above to get it working.
my jscript above to get it working.
I was trying to get to a point where I could write my JQuery in such a way that it could be written in javascript. Can anyone help me do this?
Thanks
EDIT
Thanks for all the answers/corrections: what I was looking for part 3 was this enter link description here which basically does part 1 using javaScript,I think. In future I should be careful,using left hand pane, to include Jquery library and to make sure jsript is wrapped in head/body
jQuery
You need to include jQuery library to your page by selecting a jQuery version in the first dropdown in the left panel
Demo: Fiddle
JS Sample
The problem is since your function is defined within the onload callback, it was not available in the global scope causing an error saying
Uncaught ReferenceError: myFunction is not defined
The solution is to add the script to the body elements, instead of inside the onload callback by selecting No Wrap - in <body> in the second dropdown in the left panel
function myFunction()
{
alert("Hello World!");
}
Demo: Fiddle
jQuery is library of javascript function and you need to add jquery file in html file that y jquery function was not working and for javacript function you need to change the setting in jfiddele left to no-wrap in head
http://jsfiddle.net/aLhb8/1/
http://jsfiddle.net/hushme/QaHda/10/
here is code
$("button").on("click", function () {
$("p").text("this text will now appear!!")
});
If you have internet connection, This should work
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
$(document).ready(function() {
$('button').click(function() {
alert("This is a simple alert message");
});
});
But if don't then just download the jquery framework and include into your page
Hope it helps and anyway jquery is a framework of javascript, so they are both or they are the same. Don't confuse yourself.
Here is a JavaScript version - http://jsfiddle.net/aLhb8/4/
JavaScript
var myButton = document.getElementById('myButton');
myButton.addEventListener('click', function(){
alert(myButton.textContent);
});
Check this link out if you want to start learning more about JavaScript - http://javascriptissexy.com/how-to-learn-javascript-properly/
For the pure JS code, on the top left panel, select 'No wrap - in body'. This will make your code run without a problem.
In the jQuery code, make sure you've selected the jQuery library, as opposed to pure JS. You hadn't selected this before, so your code was invalid.
I am coding a big website but I have cut down my problem into the following tiny html file:
http://dl.dropbox.com/u/3224566/test.html
The problem is that if I (re)load with JQuery a content that features a facebook code, the latter won't appear, even if I reload the script (leading to a duplication of that all.js script, which is another issue).
How can I fix this?
Regards,
Quentin
Use the FB.XFBML.parse() docs after you load the new content
function loadPage() {
$('#test').load('test.html #test', function() {
FB.XFBML.parse( );
}).fadeOut('slow').fadeIn('slow');
}
Note, that loading a fragment with id test in a div with id test will create multiple (two) elements with the same id (nested in each other) in the page, which should never happen as it is invalid.
To avoid this use the more verbose $.get method
$.get('test.html',
function(data) {
var temp = $('<div>').html(data).find('#test');
$('#test').html(temp.html());
}
);
I'm using jQuery Mobile and Backbone JS for a project. It's mostly working, using jQuery Mobile's event 'pagebeforeshow' to trigger the correct Backbone View. In the Backbone View for that particular jQuery Mobile page, that's where it's doing all the dynamic things needed. Some of the things the views do is pull in certain bits using Underscore's templating system.
This is all great until where I pulling in form bits using the templating system. For example, a set of dynamic radio buttons (which are generated from a Backbone Collection). These radio buttons I want to style up using what jQuery Mobile has to offer. At the moment, jQuery Mobile is not picking up these dynamically injected radio buttons. I solved this issue previously when doing sliders by just calling the jQuery Mobile widget "slider()" method again and it seemed to refresh them... This doesn't seem to be the case with these radio buttons.
In the Backbone View, I tried calling the widget methods again:
$(this.el).find("input[type='radio']").checkboxradio();
$(this.el).find(":jqmData(role='controlgroup')").controlgroup();
I tried them the other way around too, but it seemed I need to do it this way for the grouping styling to work etc. But this just doesn't seem right! ...doing this also caused errors when I clicked on the radio buttons, saying: "cannot call methods on checkboxradio prior to initialization; attempted to call method 'refresh'"?
It seems there should be a way in jQuery Mobile to re-initialize the page or something?! I noticed there is a 'page' widget in the source code.
How does jQuery Mobile handle forms/elements being injected into the DOM after the page is made? Is there a clean way of handling how it makes up the forms? There must be a clean way of calling on the forms to render 'the jQuery Mobile way' without it just relying on data attribute tags in the base HTML?
Any help or insight into this problem would be greatly appreciated... I'm very much on this quest of trying to get Backbone JS and jQuery Mobile to work nicely together.
Many thanks, James
update
Since jQueryMobile beta2 there is an event to do this. .trigger('create') on an element to cause everything inside it to be painted correctly.
Another question that is not a duplicate, but requires an answet I posted over 10 times :)
[old answer]
try .page()
More details in my faq:
http://jquerymobiledictionary.pl/faq.html
Refreshing the whole page worked for me:
$('#pageId').page('destroy').page();
I'm not sure if this helps but when adding dynamic elements I was using .page() in the sucess ajax call itself (example here and here) but I found that it was not working as expected. I found that in the ajax call it's better to refresh the element (if it's a form element) to use these documented methods:
Checkboxes:
$("input[type='checkbox']").attr("checked",true).checkboxradio("refresh");
Radios:
$("input[type='radio']").attr("checked",true).checkboxradio("refresh");
Selects:
var myselect = $("select#foo");
myselect[0].selectedIndex = 3;
myselect.selectmenu("refresh");
Sliders:
$("input[type=range]").val(60).slider("refresh");
Flip switches (they use slider):
var myswitch = $("select#bar");
myswitch[0].selectedIndex = 1;
myswitch .slider("refresh");
and for adding a non-form element use .page()
JQuery Mobile now supports .trigger("create"); which will resolve this for you
Try calling .trigger("create") on the element with the new content.
I needed a way to dynamically refresh a JQM page after it had been initialized. I found that if I removed the data attribute "page" during the "pagehide" event, the next time the JQM page was displayed it was re-initialzed.
$('#testing').live('pagehide', function (e) {
$.removeData(e.target, 'page');
});
$('#pageId').page('destroy').page();
works for entire control groups that are generated, let alone radio input children.
-Mike
It worked for me when I called .trigger('create') on the enclosing div element. See example below:
In .html file:
<div id="status-list" data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>Choose as many snacks as you'd like:</legend>
<input type="checkbox" name="checkbox-1a" id="checkbox-1a"/>
<label for="checkbox-1a">Cheetos</label>
</fieldset>
</div>
in .js file:
$("#status-list").trigger('create');
For me only .page() worked (without the .page('destroy')).
E.g.:
$('my-control-group-id').page();
Amnon
I little bit off topic. I wanted to be able to stop jqm from creating first default page div on init as backbone wraps elements in divs anyway. I wanted to dynamically insert pages to the DOM and then call jqm to create its classes and widgets. I finally did this like this:
<head>
<script src="jquery-1.8.3.js"></script>
<script type='javascript'>
$(document).on("mobileinit", function () {
$.mobile.autoInitializePage = false;
}
</script>
<script src="jquery.mobile-1.3.0-beta.1.min.js"></script>
</head>
<body>
....... dynamically add your content ..........
<script type='javascript'>
$.mobile.initializePage()
</script>
</body>
and my hole jqm config (which you put before jqm.js)
$(document).on("mobileinit", function () {
$.mobile.ajaxEnabled = false;
$.mobile.hashListeningEnabled = false;
$.mobile.pushStateEnabled = false;
$.mobile.linkBindingEnabled = false; // delegating all the events to chaplin
$.mobile.changePage.defaults.changeHash = false;
$.mobile.defaultDialogTransition = "none";
$.mobile.defaultPageTransition = "slidedown";
$.mobile.page.prototype.options.degradeInputs.date = true;
$.mobile.page.prototype.options.domCache = false;
$.mobile.autoInitializePage = false;
$.mobile.ignoreContentEnabled=true;
});
So far Backbone and JQM been working fine.
Try use enhanceWithin() method. This should be method of any jQuery object while using jQuery Mobile.