$(document).foundation(); not working - javascript

I try to get my elements, that I load via ajax back to work but when I try to reinitialize the events on them, it simply doesn't work.
I tried to insert $(document).foundation(); on different places in my code but nope :(
Here an example:
$.ajax({
url: 'dashboard/ajax/links/get',
method: 'post',
data: {
_token: $('input[name=_token]').val()
},
success: function(data) {
$('.links-container').html(data);
$(document).foundation();
}
});
Any ideas?
Update
Another example
// open edit link modal
$('.item-link-edit').on('click',function(e){
e.preventDefault();
// get item id
var id = getItemId(this);
// open modal and load content
$('#edit-link-modal').foundation('reveal','open',{
url: 'dashboard/ajax/links/modals/edit',
data: {
id: id
},
success: function() {
setTimeout(function(){
$(document).foundation();
console.log('reinit');
},1000);
}
});
});
still not working :/

You need to use reflow if you add new content to the DOM.
$(document).foundation('reflow');
Reflow will make Foundation check the DOM for any elements and re-apply any listeners to them. If you dont want to reflow everything you can specify the module you want to re-apply;
$(document).foundation('orbit', 'reflow'); // orbit, for an example
Further documentation can be found here:
http://foundation.zurb.com/docs/javascript.html

Related

How to use afterRender and rebuild from fullpage.js

I've read the documentation regarding afterRender from the fullpage.js github page. In my site I have content that is generated by AJAX in a particular div.
Example below
$("#fullpage").fullpage({
afterRender: {
// I don't know what to put here
}
});
$("#btn-generate-content").on("click", function() {
// Target the div
$.ajax({
url: "get_topic_content.php",
dataType: "json",
success: function(data) {
// Place the data in the div
}
});
});
With the code above, I'm generating a long paragraph and placing it into a div. Now I want my site to resize accordingly to the generated paragraph. How can I use reBuild() on the afterRender to target this particular div when it has finished rendering the content.
After get ajax content you should use $.fn.fullpage.rebuild() in a callback.
I don't see an action of placing html content.
It should be done in success function, and then you should call rebuild function.

Event handling in dynamically generated page

I have a div with class called 'taglines' which is contained in a div with class called 'container'. When 'taglines' is clicked, it navigates to another page. The problem is the events on this new page are not responding after navigation. The following is the code that I am using to navigate:
$(document).ready(function(){
$('.container').on('click', '.tagLines', function(){
window.location = "manageMarks.php";
});
}
The following is the code with the event that is refusing to work after navigation:
$(document).ready(function(){
$('.container').on('click', '.loadSub', function(){
alert('Clicked');
});
});
However, If i use ajax to load the new view I want, the events do eventually work. The following is the ajax I code I am using:
$(document).ready(function(){
$('.container').on('mouseover', '.tagLines', function(){
$.ajax({
type: 'GET',
url: 'manageMarks.php',
data: {
videoCode: $(this).attr('data-code')
},
success: function(data){
//alert(data);
$('.container').html(data);
}
}).error(function(){
alert('An Error Has Occured');
});
});
How can I get it to work without using ajax?
Are you doing a full page reload? If so your events would need to be wired up again. If not they should get wired up to dynamically loaded content.

Appending a Div tag not working properly

I am developing MVC 3 application and using razor syntax.
In this application I am giving commenting facility.
I have given the facility to adding a comment and it saved in DB.
and when user clicks on delete button it displays the message as "Clicked".
When user load entity, previously added comments get displayed on page with
delete button and when user click on that button the "clicked" msg appears.
now, when user add a new comment, it saved in DB sucsessfully and also appear on the page
along with Delete button.
now when user click on delete button msg wontcome...
( I append the Div tag while loading the new comment from DB)
I think , there is a issue regarding append, means previous comments Delete button
work well, but when I add button using append it wont works...
Here is the code, saves comment in DB and in sucsess , it creates HTML Code with button to disply the data on the page.
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#AddCommentButton').click(function ()
{
if (document.getElementById('Comment').value != "")
$.ajax({
type: 'post',
url: '/Comment/SaveComments',
dataType: 'json',
data:
{
'comments' : $('#Comment').val(),
'EType' : #Html.Raw(Json.Encode(ViewBag.EType)),
'EId' : #Html.Raw(Json.Encode(ViewBag.EId))
},
success: function (data) {
$("p.p12").append('<button type="button" id = "1" class="deleteComment">Delete</button><br />')
alert(data.Id);
}
});
});
});
</script>
and user clicks on Delete Button I have written this code.
$(document).ready(function () {
$(".deleteComment").click(function ()
{
alert("Clicked");
});
});
For previous comments, when user click on the delete button "Clicked' msg comes but when user clicks on newly added comment's delete button, msg wont come ...
You need to subscribe to the click event of this delete button in a lively manner since it was added dynamically to the DOM. You cannot just use .click() in your document.ready because the delete button doesn't yet exist at this stage. So depending on the jQuery version that you are using there are 3 ways:
.on(), .delegate() or .live().
The recommended approach is .on() which is supported starting from jQuery 1.7:
$(document).on('click', '.deleteComment', function() {
alert("Clicked");
});
And you no longer need to wrap this in a document.ready.
If you are using an older version here's the same with .delegate() (introduced in jQuery 1.4.2):
$(document).delegate('.deleteComment', 'click', function() {
alert('Clicked');
});
And if you are using an even older version of jQuery, well, you should upgrade and if you don't want to upgrade use .live():
$('.deleteComment').live('click', function() {
alert('Clicked');
});
And while I am at your code here are a couple of other remarks.
Replace:
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
with:
<script src="#Url.Content("~/Scripts/jquery.js")" type="text/javascript"></script>
and also replace:
url: '/Comment/SaveComments',
with:
url: '#Url.Action("SaveComments", "Comment")',
And by the way as an alternative to putting the url in your javascript you could directly use the value of your AddCommentButton. You haven't shown it your markup I assume that it might look like this:
#Html.ActionLink("Add a comment", "SaveComments", "Comment", null, new { id = "AddCommentButton" })
And now all that's left is to unobtrusively AJAXify it:
$(document).ready(function () {
$('#AddCommentButton').click(function (evt) {
evt.preventDefault();
var comment = $('#Comment').val();
if (comment == '') {
alert('Please enter a comment');
return;
}
$.ajax({
type: 'post',
url: this.href,
data: {
comments : comments,
EType: #Html.Raw(Json.Encode(ViewBag.EType)),
EId: #Html.Raw(Json.Encode(ViewBag.EId))
},
success: function (data) {
// You probably need to embed the comment id as a HTML data-* attribute
// to the button instead of using a hardcoded id="1" value
// which by the way is an invalid value of an id in HTML:
$('p.p12').append(
$('<button/>', {
'class': 'deleteComment',
'html': 'Delete',
'data-id': data.Id
}).after($('<br/>'))
);
}
});
});
});
and now inside your Delete button click callback you will be able to access the id of the comment to be deleted:
$(document).on('click', '.deleteComment', function() {
var commentId = $(this).data('id');
// TODO: delete the comment
});
Absolutely never hardcode urls in an ASP.NET MVC application. Always use url helpers to generate them. The reason for this is that url helpers take into account the routing setup and the virtual directory in which your application might be running. So if later you decide to change the pattern of your routes or even deploy your application in IIS you will no longer need to go through all your pages and replace those wrongly hardcoded urls for your application to work.

Hyperlink's click even not triggering in jQuery

Here is my full JS code:
var timeOutId;
function ft(){
$.get("progress.txt", null, function(data){
if(data.substr(0,10) == "MSG::MSG::"){
$("#box").html(data);
window.clearTimeout(timeOutId);
}else{
$("#box").html(data);
}
});
};
$(document).ready(function(){
$("#box").corner('20px');
$("#progress").hide();
});
$("#newm").click(function(){
$("#progress").show();
$("#list").html = $.ajax({
url: "action.php",
global: false,
type: "POST",
data: ({keyword : $("#keyword").value()},{format: $("#format").value()},{filename: $("#filename").value()},{list: $("#list").value()}),
dataType: "html"
});
timeOutId = window.setTimeout("ft()", 10000);
});
and there is a hyperlink with ID "newm" on page but clicking on the link doesnt trigger the ajax request. Can anyone tell me what is wrong?
Description
I have tryed your code and recognize that your binding to click is not working because the DOM element is not available at this time.
You should bind it under $(document).ready() to ensure the DOM is fully loaded before binding javascript / jquery to that.
This will enusre that your link will work, but its hard to help you without the html source.
If this will not help, please post the html.

How to update a value by jQuery AJAX

I load content of a page by jQuery AJAX as
$(document).ready(function(){
$('#next').click(function(event){
$.ajax({
url: "load.php?start="+$('#lastid').text(),
success: function(html){
$("#results").append(html);
$("#lastid").empty().load('html #start');
}
});
});
});
In the current document, I have <div id="lastid"></div> and in the external php file <div id="start"></div>
The value for id="start" is updated from database, and it will be transferred to id="lastid". However, this code only works for FIRST click. For default <div id="lastid">1</div>, when clicking the button (id="more") it will read load.php?start=1 and updates the current document to <div id="lastid">11</div> (it's visible). But the second click will not load load.php?start=11
It seems that $('lastid') well reads the default value of <div id="lastid"></div>, but NOT when it has been updated by $("#lastid").empty().load('html #start')
How can I modify this code to work for subsequent clicks?
Wow, what a mess! Let's clean up a bit :)
You need to get rid of the id, as an id has to be unique and if you load another div with id lastId into your site, jQuery will not know which id to get. If you have many divs, each containing the id, you can just read the last id by using ('div:last').text();
So your ajax would look like this:
$(document).ready(function(){
$('#next').click(function(event){
$.ajax({
url: "load.php",
data: "start="+$('div:last').text()
success: function(html){
$("#results").append(html);
}
});
});
});
I also don't know what you do with the last line in the success, as load should be used to load data from the server with ajax, what is what you do by using $.ajax(). Also load() takes at least an url as parameter, see here.
try .live() function instead of .click()
Mate,
What I see from you code is that you are attaching an event once the page is loaded. And this creates a static call with static values that don't get updated as you continue.
My suggestions is to use a function that will feed an Id dynamically to your ajax call as follows:
$(document).ready(function(){
$(document).on("click", '#next', function(event){
$.ajax({
url: buildurl(),
success: function(html){
$("#results").append(html);
$("#lastid").empty().load('html #start');
}
});
});
});
function buildurl()
{
return "load.php?start="+ $('#lastid').text();
}
This will force your event to always call this function and the function to get a fresh value from lastid.
Regards
you have to change your success function because you have multiple #lastid when clicking twice.
try something like:
success: function(html){
$("#lastid").removeAttr("id"); // remove's the id from #lastid
$("#results").append(html); // appends the new one
$("#lastid").empty().load('html #start');
}

Categories