I have a rails app, if the user is not logged in, I am redirecting to a page, which has one br tag with a class. Like this
<br class="logged">
In the Javascript on ready of that function, I am triggering a modal as follows.
$(document).ready(function(){
$('.logged').ready(function(){
$('#open-login').click();
});
});
This is working fine, except this modal is getting triggered on every page of the app. I mean that br tag is there in only page of the app, how it is ready for every page is what I don't understand. If anyone can tell what went wrong with my approach, it would be of great help.
ps: It's rails application
You can try this:
$(document).ready(function(){
if ($('.logged').length > 0)
$('#open-login').click();
}
});
Into if condition you can declare an element of specific page and in only that page you can execute an action.
The jQuery .ready() method can only be called on a jQuery object matching the current document. Attaching it to a $('.logged') selector still makes its handler function get called when the document is ready - it doesn't care about the selector.
MarcoSantino's answer will work for your needs, although you may find it cleaner to add the logged-in class to the body tag instead of inserting a new br tag, and then use the following in your JavaScript:
$(document).ready(function(){
if ($(body).hasClass('logged-in')) {
$('#open-login').click();
}
})
Related
I have the following JS code:
<script type="text/javascript">
$(document).ready(function () {
var items = "<option value='0'>Select</option>";
$('#DistrictID').html(items);
});
</script>
This populate a dropdownlist with the value Select, the thing is, this dropdownlist appears in a form that it's called once the user clicks a button and then a modal windows opens, with the form in it.
But since it is mark as
$(document).ready
This JS won't execute with the modal, since the document is already 'ready'. How can I achieve this?
Thanks in advance!
Regards,
You can easily achieve this using bootstrap modal events. You can use following code snippet to achieve your objective:
$(document).ready(function () {
$('#myModal').on('shown.bs.modal', function (e) {
var items = "<option value='0'>Select</option>";
$('#DistrictID').html(items);
});
});
For reference Please check bootstrap modal events.
A useful way to load and execute javascript after the page is loaded, like modal window show ups, is to use ajax getScript function, which Loads (and executes) a JavaScript from a server using an AJAX HTTP GET request through a pre-defined function in main page.
function loadJS(lnk){
$.getScript(lnk);
}
it can be a general way to load any script in a fully loaded page.
One solution is to use jQuery event.on
from this blog post https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html
I will quote the author, because I think it's a very neat explanation.
We can’t register a listener to an element that doesn’t exists.
A work around is to register the listener to an element that will
always exist in the page context. The #modal-book is the closest
element. It is a little bit more complex what happen, but long story
short, the HTML events propagate to the parents elements until it
reaches the end of the document.
More here: https://api.jquery.com/on/
Try something like this:
$('#idofselectelement').change(function() {
//grab the selected option and then do what you want with it.
});
Please have a look. EDIT: here is a link to a fiddle for the entire code: http://jsfiddle.net/e77aqubx/
This is a section of the jQuery (everything above it seems to be working fine). I am trying to get portfolio.html to show up in the #portfolio div (which is not visible until you click the link for it). The portfolio.html is in the same folder in the directory so I don't think I have to worry about the link.
$("#portfolio_link").click(function(){
$(".header").hide();
$("#about").hide();
$("#portfolio").show();
$("#portfolio").load("portfolio.html");
});
I have a div set up for it in the html as
<div id="portfolio">ooh blah dee</div>
In the jQuery I also tried:
$("#portfolio").show(function(){
$("#portfolio").load("portfolio.html");
});
Have you considered using IFrames? If I understand your issue correctly you can simply change the display of the element on action using something like .toggle()
example: JSFiddle
Edit:
As far as the current code, i would really need to see some more info as your code appears, at a simple form anyway, correct. Can you provide your file structure, or the results from the networking tab in dev tools when you run the event? Or even give this a shot on your .load():
$( "#portfolio" ).load( "portfolio.html", function() {
alert( "Load was performed." );
});
However it's important to remember that .load() is an ajax call so everytime you run your display method you're rendering a view via ajax instead of that one time iframe.
Hmm, the problem might be that the #portfolio_link element is created in the DOM after you attempt to attach the event listener. This could be solved by attaching the event listener to the 'body' tag and filtering down to any click events on children matching the '#portfolio_link' DOM selector.
Try this:
$('body').on('click', '#portfolio_link', function(){
$('.header').hide();
$('#about').hide();
$('#portfolio').show();
$('#portfolio').load('portfolio.html');
});
Jquery works in chain.
Also try first to load and then hide.
Can you use Firebug or Chrome devoper tools to see
what is happening with DOM?
I'm building a JQuery mobile site which has an image slider on 2 pages. The sliders are activated using the following JS:
$(function () {
$("#slider").excoloSlider();
});
where '#slider' is the name of the div that gets rendered as the slider.
I have this slider on the 2 pages and have given both the same id, and don't want to insert the above code into both pages. To make things easy I want to be able to make add the above code into a.js file that I'm referencing at the top of both pages.
However, the script only kicks in when one of the pages are the first page to be navigated to. So, I assume this means the code is only being called in the once, and due to the AJAX loading of the subsequent page, it isnt called when this new page loads.
So, how can I run the code to affect any/all pages which feature the slider?
I dont know how many times you have to call .excoloSlider(); function. In case you have to call it each time the page is visited, then you need to use any of these page events, pagecontainershow or pagecontainerbeforeshow.
If you use pagecontainershow, you can run .excoloSlider(); on #slider even if you have the same id in a different page. This way, you specify in which page to look for #slider.
$(document).on("pagecontainershow", function () {
var activePage = $.mobile.pageContainer.pagecontainer("getActivePage");
/* check if #slider is within active page */
var slider = activePage.find("#slider").not(".slider");
if(slider) {
slider.excoloSlider();
}
});
Update
I have added .not(".slider") selector to exclude already rendered slider. The function .excoloSlider() will be called on new sliders only.
Demo
Try to use class instead of id since id is unique, then you can change your jQuery code to:
$(function () {
$(".slider").excoloSlider();
});
Use jQuery Mobile API for the navigation system
$(window).on( "navigate", function( event, data ) {
$("#slider").excoloSlider();
});
Edit
Use pageinit
From the jQM docs:
Important: Use $(document).bind('pageinit'), not $(document).ready()
The first thing you learn in jQuery is to call code inside the
$(document).ready() function so everything will execute as soon as the
DOM is loaded. However, in jQuery Mobile, Ajax is used to load the
contents of each page into the DOM as you navigate, and the DOM ready
handler only executes for the first page. To execute code whenever a
new page is loaded and created, you can bind to the pageinit event.
This event is explained in detail at the bottom of this page.
I am using jQuery Mobile to create a site, in the index page I placed here a form for a search. I hooked submit event for ajax post. When ajax success get the resource
(html,<ul>...</ul>), placed in the target container, then trigger the create event for enhance the view. This work fine in the first time. When I click back to index page and search again I got a raw listview without enhance, who can tell me why? ps: I have tried many methods but there is more and more problem, the official document was so poor.
$(document).bind('pageinit',function(){
$("#search").submit(function(){
var searchdata = $("#search").serialize();
$.ajax({
'type':"POST",
'url':"/server/jnulib.php?action=search",
'data':searchdata,
'success':function(data){
$("#searchresultfield > ul").remove();
$("#searchresultfield").html(data).find('ul').trigger('create');
try{
$("#searchresultfield > ul").listview('refresh');
}catch(e){
}
$.mobile.changePage("#searchresult");
//$("div[data-role='header'] > a").
}
});
return false;
});
});
EDIT: Test Url: http://ijnu.sinaapp.com
Another problem: the second ajax request failed and the browser navigate to the ajax target straightly.
You could try changing:
$("#searchresultfield").html(data).find('ul').trigger('create');
to:
$("#searchresultfield").html(data).find('ul').listview().listview('refresh');
Anytime you append or remove elements you need to refresh, and if you remove the whole list, you need to reinitialize it.
Also I have had issues with listview('refresh') rendering improperly if it was not visible.
$(document).on('pageshow','div',function(event, ui){
if($("#searchresultfield > ul").is(":visible")) $("#searchresultfield > ul").listview('refresh');
});
For me, .trigger('create'); always works if applied to the element with data-role="page"
For example
HTML Code
<div data-role="page" id="somePage">
...
</div>
Javascript Code
$('#somePage').trigger('create');
Hope it helps
Try:
$("#searchresultfield > ul").empty();
instead of
$("#searchresultfield > ul").remove();
I think the problem is that jquery mobile loads all pages despite all being from different files into one big page and navigation is based off going to different points in this page, so that when you go onto it the first time the page you access is considered created however when clicking the back button and navigating away from the page that page is still considered created so the event well not fire again,
What I used was:
$('#oppList').live('pageshow',function(event){
getList();
});
Where #opplist is the id of the data-role="page" for the page I just load, this does not matter whether this happens the first time the page is loaded or after because the event is fired whenever the page is displayed.
See Here foe jquery mobile events
Also see here for jquery mobile navigation
Hope this helps !
Maybe you should try to unhook the submit event once it's been handled. And initiate it again once you go back to the page where you were before. Adding eventhandlers multiple times can cause a lot of problems.
I'm working on a extension for a fb game that adds some extra info to popup boxes, hides some useless information and run some timers so you can see how long till you have to do something even if you are not on the game page.
My problem is that a while back they went over to using ajax to change between pages and I am wondering if I am using the right approach to handle this.
I run a setInterval that checks if I am on a page where i want to add/remove soemting and i havent done it yet, if this is true I do my stuff, the code looks something like this:
function myFunction() {
if($(selector for some element I am looking for).length > 0 && $(selector for some item I add).length == 0) {
//do some stuff
}
}
setInterval("myFunction()",1000);
Is this the right way of handling ajax page change from an content script in an extension?
If so is there a better way to see if I am on the right page or if i have added to this page already other than doing a selection?
You can use livequery jquery plugin to catch when new element is created on a page:
$("#ajax-element").livequery(function({
//ajax-element is created
});
You can also listen to DOMSubtreeModified event which fires when DOM changes:
document.addEventListener("DOMSubtreeModified", function(event){
//something has changed, possibly ajax-element was added
});
There are also more specific DOMNodeInsertedIntoDocument and DOMNodeRemovedFromDocument events.