Making jQuery .on() work with Rails 3 - javascript

I'm building a Rails 3 app, and trying to get the jQuery .on() function working. It's currently not doing anything.
In assets/javascripts/v-application.js:
console.log('application');
$('body').on('click', function(){
alert('test');
});
When the app loads, the console displays "application" (as it should), but when I click on the body, no alerts fire. If I paste that exact same javascript into the console and click on the body, the appropriate alert fires.
If I view v-application.js in the browser, it shows the function.
I am using the latest versions of jquery-rails (2.0.1) and rails (3.2.2). This is all in the development environment.
What's going on that Rails doesn't know how to handle that basic function call? Does this have to do with the asset pipeline? How can I get that working?

I'm going to guess that you don't have a ready function.
$(function() {
$('body').on('click', function(){
alert('test');
});
});
If you stick the code directly in the main JS file, doing $('body') will not find anything, because when the script tag is interpreted, the body tag hasn't been processed yet. Sticking the logic inside a ready function will wait for the whole document to be parsed.

Are you using jQuery 1.7.1? That's when .on came about, had the issue before.
jsFiddle here: http://jsfiddle.net/LmC6x/
As #loganfsmyth said though, I'd recommend using the ready function.

Related

Call JavaScript function when div is loaded in Partial Page in MVC

I have a Partial page in which I am loading div elements. I want to call a JavaScript function when each div is loaded in my partial view.
<p class="m-0" onload="markMessageAsDelivered('#item.isDelivered')">#item.Message</p>
This is the function I have in my JS in my razor page.
function markChatAsDelivered(isDelivered) {
if (!isDelivered)
alert('markChatAsDelivered');
}
This function is not getting called. I tried to put it in windows onload as well but still it is not working. Please let me know what can be done?
The problem I've had with these things is that onload is called before ASP.NET makes its changes to the page. There's two solutions I use:
$(document).ready() with JQuery waits until the DOM is fully loaded and done, so you can migrate some code into there.
function pageLoad(sender, args) is a built-in ASP JS function (like Page_Load in your code behind) that gets called when the page is done being loaded. You can migrate some JS into here like the first answer.
Personally, even though I like to avoid libraries, I like the first option because you can use more than one per page. This is only really useful if you're calling code in your master page though. The second option is good if you only use it once per page, but obviously if you try to use it in both your master page and current page, it won't work properly. So I'd recommend JQuery, but if you must avoid it, pageLoad works too.

How do I get a jquery function to run when the page is loaded?

I'm trying to create an html page that uses jquery to populate a table when the page loads. I have the function that gets the data, but currently for testing I just attached it to a button that I'm clicking to get the table to appear.
How do I get a jquery function to run when the page is loaded? In case it isn't obvious I'm a complete beginner when it comes to Jquery, so this may be something really obvious, but I've been trying to google it and I can't find a solution.
This should do the trick
jQuery(document).ready(myFunction);
function myFunction(){
// logic goes here
}
jQuery(document).ready(function(){
//some logic
newFunc();
//logic
});
function newFunc(){
//logic
}
However you can write code anywhere inside <script> tags and it will execute directly after including the jQuery file. But, the may not be as effective as above because at that time dom may or may not be created. So, better go the above way .. as it will only execute when page is loaded and DOM is created.
Are you looking for something like this. You can do this in regular JS.
document.addEventListener('DOMContentLoaded', function() {
console.log('document loaded');
});
But be aware this doesn't cover you from other dependent file loading like the js and png and others . They get loaded asynchronously . this just cover you for the dom content load

ColorBox - Error: cboxElement missing settings object

What I'm trying to do is to play a video inside ColorBox lightbox.
My HTML code is as follows. When I click on the link it should play the video.
Video
What I do with Colorbox is as below. Load the video into lightbox.
jQuery(".iframe").colorbox({iframe:true, width:"80%", height:"80%"});
It gives me the below error.
Error: cboxElement missing settings object
ScreenShot
What should I do to fix this ? Given that there are no js errors except above one. jQuery is included correctly.
I had the same problem. I'm having a hard time trying to understand why exactly, but somewhere the colorbox is running in to a conflict because it also uses the name 'iframe' internally. Somehow this is causing a conflict when the classname 'iframe' is used as the class by which the function is called.
In my case changing
jQuery(".iframe").colorbox({iframe:true, width:"80%", height:"80%"});
to:
jQuery(".photo_link").colorbox({iframe:true, width:"80%", height:"80%"});
worked.
Well this worked for me. Even though everything was in place and all the code was generated in the backend, for some reason colorbox wasn't picking up the links properly because on my page the link was inside a div that shows/hide on mouseover. Anyway, the way it worked for me was this one:
$(".iframe").live('click', function(e){
$(this).colorbox({href: $(this).attr('href'), iframe:true, innerWidth:640, innerHeight:480, open:true});
e.preventDefault();
return false;
});
In this way you rebind the actions to the element and then forces colorbox to open the link.
I hope it works for you and it isn't too late.
PS: If you're using jQuery 1.9+ you must use on instead of live
I ran into this same error and solved it by removing a duplicate call to colorbox. I had included both the library as well as my colorbox function in two separate include files. I figured it must be a duplicate because I had to close each colorbox window twice after it launched.
Check your code and make sure that the jquery.colorbox-min.js is only included once, as well as your function that calls it. In my case, my function was simple:
$(document).ready(function(){
$("a.single_image").colorbox();
$("a.link_preview").colorbox({iframe:true, width:"80%", height:"90%"});
});
After removing the duplicate calls, the problem went away. Hope it helps!
I experienced this error Error: cboxElement missing settings object when making a second jQuery on document ready function call after the initial on document ready function call that holds the colorbox parameters.
My situation:
On my pages I use and call just one external .js file that holds all
my code.
Inside the external .js file I have the colorbox parameters within a
jQuery on document ready function.
On the troubled page (page with cboxElement missing settings object
error), immediately following the external .js file I had some
jQuery code that used the on document ready function: $(function(){});
My problem:
This second on document ready call caused and triggered the error Error: cboxElement missing settings object for me.
My solution:
The fix was as easy as changing the troubled pages code from using jQuery's on document ready function to using Javascript's native self-executing anonymous function.
(function(){
})();
Sure enough the error Error: cboxElement missing settings object went away and everything works perfect!

How to execute custom js after jQuery Mobile has created a new page div?

So I am using Django 1.3 and jQuery Mobile for a webapp. When trying to create new functionality or override some of jQM's functionality I don't seem to be able to get it to excute some code on page creation. I am still hackish at js, but it seems to be a bigger problem than myself
How to execute JavaScript after a page is transitioned with jQuery Mobile
I end up putting js snippets on the page itself which doesn't seem the correct way to handle they work sometimes and sometimes not. I have tried the same commands in the script console of Chrome and the selector and commands seem to work fine.
examples:
Hiding the numeric inputs on on sliders I end up putting this script tag in the template itself, I know this is bad form, but am unsure how to get it to work otherwise:
<script>
$('#form_div > input').hide();
</script>
Trying to do a similar snippet:
<script>
console.log("Focus snippet!");
$('.ui-input-text').blur(function(){
console.log("focus was changed!");
});
</script>
yields no results, except the initial console.log, but I can execute through the script console and it works fine.
I saw in this several other posts, but none have seemed to answer the question clearly and I am unsure how how to make this work the right way.
This seemed the closest suggestion, but I was unable to make it work:
Jquery mobile: how to execute custom jquery code in page
$(“body”).delegate(“div[data-role*='page']“, “pageshow”, function(){
// Your code here. It is good to check to not run unnecessary code
});
Any suggestions would be greatly appreciated.
Look at the documentation here: http://jquerymobile.com/demos/1.0a4.1/#docs/api/events.html
$('div').live('pageshow',function(event, ui){
alert('This page was just hidden: '+ ui.prevPage);
});
$('div').live('pagehide',function(event, ui){
alert('This page was just shown: '+ ui.nextPage);
});
One small note is that all the javascript executed on any page must go in the base page (like: index.html). If you add javascript for page2.html in page2.html it will not be executed. if you add the javascript for page2.html in index.html it will be executed.

using load() to load page that also uses jQuery

I'm trying to load a page that is basically an edit form inside a
dialog (ui.dialog). I can load this page fine from an external (I'm
using asp.net) page.
The problem is that inside of my "popup" form, I need to $(function()
{my function here}); syntax to do some stuff when the page loads,
along with registering some .fn extensions for some dynamic dropdowns
using ajax calls.
I have created my <script type="text/javascript" src="jquery.js"> but
I don't think these are being included, and also my $(function) is not
being called.
Is this possible to do or do I need to find another way of
accomplishing what I need to do?
If you really need to load that form via AJAX you could to do all the Javascript stuff in $.ajax callback itself.
So, you load the popup form like this:
$.ajax({
//...
success: function(text) {
// insert text into container
// the code from $(function() {});
}
});
The script isn't getting run because the document's ready event has already been fired. Remove your code from within the
$()
Use the livequery plugin.
It allows you to bind events to elements that might be loaded later: http://brandonaaron.net/docs/livequery/

Categories