javascript code only work once, when page is loaded - javascript

Hi I have this HTML code:
<ul class="nav navbar-nav navbar-right">
<li>
<%= link_to "Articulos", articulos_path, id: "ajax_articulos" %>
</li>
</ul>
and whenever someone click on #ajax_articulos I want to trigger:
$(document).ready(function(){
$( "#ajax_articulos" ).click(function() {
alert( "Handler for .click() called." );
});
});
My problem is that it only works at first when the page is loaded. Once the page is loaded if I click again it will not work.
How could I make that action work again even when used without having to refresh the page ?

Which version of Ruby On Rails are you using?
If you're using RoR 5 or above with turbolinks you need do something like this:
$(document).on('turbolinks:load', function() {
$('.some_parent_class').on('click', '#ajax_articulos', function() {
//Handler...
}
})

You can try this event using the jquery .on():
$(function() {
$('.some_parent_class').on('click', '#ajax_articulos', function() {
//Handler...
}
})
Jquery .on() function

Related

Datepicker not working in div loaded by ajax

I have a div which is populated by ajax. When done this way the datepicker is not called. I originally had the datepicker loaded in the header of the containing page but have tgried loading it within the script which calls the div content but again no luck. The Jquery library is called in the header of the main page. If I load the pages without ajax then there is no problem and the datepicker works fine.
<li><a data-target="#halloffame" href="abscencerecords.php">Absence Records</a></li>
<li><a data-target="#halloffame" href="abscencerequestform.php">Absence Request</a></li>
<li><a data-target="#halloffame" href="personaldetails.php">Personal Details</a></li>
<?php endif ?>
<?php endif ?>
</ul></div>
<div class="clear padding20"></div>
<div id="halloffame" class="bordered_box"></div>
<script>
$('[data-target]').click( function (e) {
$(document).ready(function() { $("#datepicker").datepicker({ dateFormat: 'dd/mm/yy' }); });
$(document).ready(function() { $(".datepickermultiple").multiDatesPicker({ dateFormat: 'dd/mm/yy' }); });
var target = $($(this).attr('data-target'));
target.load($(this).attr('href'));
e.preventDefault(); // prevent anchor from changing window.location
});
</script>
Most plugins only initialize for elements that exist ... at the time the code is run
In order to initialize a plugin within ajax loaded content you need to do that within the completion callback of ajax.
Try changing :
target.load($(this).attr('href'));
To
target.load($(this).attr('href'), function(){
// new html now exists , initialize plugins or event handlers or dom manipulation here
$(this).find(selector).somePlugin()
});
Reference load() docs
In my case datepicker plugin was getting initialize, but the issue was position of datepicker calendar, I solved it by adding below CSS to the page:
#ui-datepicker-div {
position: absolute !important;;
}

how to dynamically add jquery mobile popup effect to links

In jquery mobile, I dynamically add a tags that is supposed to open a popup like in this example below. But since it is dynamically added, the jquery mobile effects don't affect it. How can I get it to work like this?
Thanks
Actions...
<div data-role="popup" id="popupMenu" data-theme="b">
<ul data-role="listview" data-inset="true" style="min-width:210px;">
<li data-role="list-divider">Choose an action</li>
<li>View details</li>
<li>Edit</li>
<li>Disable</li>
<li>Delete</li>
</ul>
</div>
When you append any html into a page after the page's initial load, you need to reapply any of the jquery functions in order for them to work when the event occurs
Example...
if you currently have something like this:
<script type="text/javascript">
$(document).ready(function () {
$('a').on('click', function () {
//something
return false;
});
});
</script>
This will do //something whenever the user clicks on any < a > link.
Now that you are loading the new < a > links in after the document is ready, the code above will not apply to the new code as it was not on the page when the javascript applied the above code.
To fix this, you need to run the function that does the //something again after the new < a > has been loaded.
<script type="text/javascript">
$(document).ready(function () {
somethingFunction();
});
});
//this is where we put the code to apply an event, it is now recallable later on.
function somethingFunction(){
$('a').on('click', function () {
//something
return false;
});
}
</script>
Assuming that you are pulling in the new < a > html via an ajax query, you would need to call the somethingFunction() after the ajax query is successful
EG
$.ajax({
type: "POST",
url: "/action" ,
dataType: 'text',
success: function(data){
$('.popups').html(data);
somethingFunction(); // THIS IS WHERE IT APPLIES THE EVENT TO YOUR NEW HTML.
}
});
If I understood correctly, you want to add buttons dinamically, resulting in the style proposed in your example:
class="ui-btn ui-corner-all ui-shadow ui-btn-inline ui-icon-gear ui-btn-icon-left ui-btn-a"
To apply jQuery Mobile enhancements after appending some HTML you have to call the widget creation method: .button(); in this case (can be .checkboxradio();, .listview();, etc).
I put toghether a JSFiddle which demonstrates dynamically creating a button calling .button() and also applying hardcoded classes (which I think it's not a good thing to do).
There is a demo available in jquery mobile documents Dynamically create popup
Following i write a simple html tags in javascript then append in to jquery mobile pages.
html:
<div data-role="page">
<div data-role="content" id="forpopup">
</div>
<div>
Here is the Fiddle Demo.
i hope this will be helpful.

Using jQuery post function, the returned link cannot have addClass function run on it

HTML
<div id="add_to_library" class="add-library-wrapper">
<a href="javascript:void(0)" class="library-select" id="library-status-select" >Click</a>
<div class="dropdown">
<ul>
<li><a onclick="create_library_entry('Complete', 123, 124);" href="javascript:void(0)">Stuff</a></li>
</ul>
</div>
jQuery
$('#library-status-select').click(function() {
$(this).toggleClass('open');
$('.dropdown').toggleClass('open');
});
function create_library_entry(status, user_id, anime_id) {
jQuery('#custom_lightbox').html('');
jQuery.post("/wp-content/themes/phanime/custom_functions/create_single_libraryEntry.php", {user_id : user_id, anime_id : anime_id, status : status}, function(data) {
//this is your response data from serv
console.log(data);
jQuery('#add_to_library').html(data);
});
}
So when I click on the anchor tag with the id of library-status-select it shows the div with the class dropdown. By adding an open class and so on. Once the dropdown shows it also has a link that does a jQuery post. The jQuery post returns it's result which in the #add_to_library id, where the link is contained. That link is replaced by another link that is returned from that jQuery.post. That link looks like this...
<a href="javascript:void(0)" class="library-select" id="library-status-select" >Click me updated</a>
It's essentially the same link with the same class / id but for some reason the jQuery.addClass / removeClass no longer works on the link that is returned from the jQuery.post. In other words the open class is not being added. If anyone knows exactly why this happens, it would be of great help.
Since you are replacing the contests you are dealing with dynamic contents so use event delegation
$('#add_to_library').on('click', '#library-status-select', function () {
$(this).toggleClass('open');
$('.dropdown').toggleClass('open');
});

Ajax not working in a jquery split button

I have a project in Codeigniter. There is a link
Edit
Clicking on the link will go to the main controller and will execute the function updatearecord. (79 is just an id).
ClientParent is called by a javascript using Ajax call
function testfunction() {
$('a.testclass').live('click', function() {
$url = $(this).attr('href');
$.ajax({
url: $url,
data: {},
dataType: 'html',
type: 'post',
success: studentSubjectCallBack
});
The link works fine anywhere on the page, but when I use it in a split button, it does not work. Here is the code for the split button
<div>
<div>
<a class="split-button"><span class="ui-button-text">Select</a>
Menu
</div>
<ul style="display:none;">
<li>Delete</li>
<li>Edit</li>
</ul>
</div>';
Can anyone help me out. I really dont understand why it is not working inside a split button
It's because you don't have testclass assigned to the a link in the second example. Your jQuery is looking for this class and can't find any elements that match.
Change:
$('a.testclass').live('click', function() {
to
$('a.editStudentSubject').live('click', function() {
As a side note, .live is now deprecated as per jQuery 1.7.1. Please use .on, such as:
$(document).on('click', 'a.editStudentSubject', function() {
Instead of :
<a class="split-button"><span class="ui-button-text">Select</a>
Try:
<a class="split-button testclass"><span class="ui-button-text">Select</a>
See: http://jsfiddle.net/leonardeveloper/8vKfb/2/

No pagechange event firing

In jQuery mobile, I am trying to detect a successful page change to a specific page. I have the following code, inline on the page I want to load.
<script>
$(document).bind( "pagebeforechange", function( e, data ) {
alert("pagebeforechange");
});
$(document).bind( "pagechange", function( e, data ) {
alert("pagechange");
});
$(document).bind( "pagechangefailed", function( e, data ) {
alert("pagechangefailed");
});
$(document).live( "pagebeforechange", function( e, data ) {
alert("pagebeforechange live");
});
$(document).live( "pagechange", function( e, data ) {
alert("pagechange live");
});
$(document).live( "pagechangefailed", function( e, data ) {
alert("pagechangefailed live");
});
</script>
I get the the appropriate alerts when loading the page directly, or refreshing, but not when navigating from another area in the Jquery Mobile app.
Page is called by the the "Your Car" Tab in the footer
<div id="footer" data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<li>Home</li>
<li>Features</li>
<li>Your Car</li>
<li>Contact</li>
</ul>
</div>
</div>
Would it work to place your code in the pageshow event? It may if you are trying to detect the page or location. Something like this maybe:
<script type="text/javascript">
$('[data-role=page]').live('pageshow', function (event, ui) {
hash = location.hash;
page = hash.susbtr(1);
if (page.indexOf('about.html') >= 0) {
alert('you made it!');
}
});
</script>
UPDATE
After testing this scenario a bit more and rereading your question, I think I was able to reproduce the results.
This works as you described and only fires alerts when loading the page directly or refreshing the page:
<body>
<div data-role="page">
<!-- page stuff -->
</div>
<script type="text/javascript"> ..bind events... </script>
</body>
However, when I move the javascript directly inside the page, it works as expected and fires all of the bound events, no matter how the page was reached:
<body>
<div data-role="page">
<script type="text/javascript"> ..bind events... </script>
<!-- page stuff -->
</div>
</body>
Where are you binding to this events?
Have you read following in the Docs http://code.jquery.com/mobile/latest/demos/docs/api/events.html:
Important: Use 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.
Luke's thinking is in the right direction: clearly the problem you had has to do with where in the code the binding is occurring. This is proved by shanabus.
However, in your case, you should be doing the binding when jQuery mobile's mobileinit event is fired, not pageInit, as Luke is suggesting.
Example (fires on all page change events):
<script type="text/javascript">
$(document).bind('mobileinit', function() {
$(document).on('pagechange', function () {
window.alert('page changed!');
});
});
</script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.js"></script>
As illustrated in the code above, be mindful that handlers triggered by mobileinit must be included before the jQuery mobile <script> tag.

Categories