Load ASP.NET MVC Partial Views Dynamically Using JQuery - javascript

I have a view with a test link on the left side. Each time user clicks the test link, I am adding a tab button and tab content (straight up HTML5 and CSS). This is what it looks like:
Controller Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MDMS_Web.Controllers
{
public class MainViewController : Controller
{
//
// GET: /MainView/
public ActionResult MainView(string name)
{
ViewBag.Name = name;
return View();
}
//[ChildActionOnly]
//public PartialViewResult MainContentPartial()
//{
// return PartialView("~/Views/MainView/MainContentPartial.cshtml");
//}
public ActionResult GetView()
{
return PartialView("~/Views/MainView/MainContentPartial.cshtml");
}
}
}
Partial View
<div id="MainContentBox" style="margin: 0em 0em;">
<h2>Testing</h2>
</div>
Main View
#{
ViewBag.Title = "Main View";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<main id="mainView">
<div class="row" style="min-width: 100%; ">
<div style="float: left; width: 20%; min-height: 870px; margin-top: 0.5em; margin-left: -1em; overflow: hidden; border-style: solid; border-width: thin; border-color: lightgray; ">
<div id="Test">
<div class="row" style="background-color: #c2cbfb; margin-left: 0; margin-right: 0; ">
<p id="menuTitle" style="width: 100%; text-align: center; margin: 5px 0 5px 0; ">Test</p>
</div>
<div class="row content-wrapper">
<span style="white-space: nowrap;">
<img class="icon" style="width: 30px; height: 30px; " src="Content/images/dashboard/CheckIcon.png" alt="Check icon" />
<a id="TestLink">Test Stuff</a>
</span>
</div>
</div>
</div>
<div style="float: left; width: 80%; min-height: 870px; margin-top: 0.5em; margin-left: 0em; overflow: hidden; ">
<div id="MainContentBox" style="margin: 0em 0em;">
<div id="tabs" class="tab">
</div>
<div id="content">
</div>
</div>
</div>
</div>
<div id="loading">
</div>
</main>
#section scripts{
#Scripts.Render("~/bundles/App/MainView")
<script type="text/javascript">
$(function () { MainView.initModule('#ViewBag.Name') });
</script>
}
JavaScript
function addTab(evt) {
stateMap.tabIndex += 1;
// add tab button
console.log(evt);
var tHtml = '<button id="tb' + stateMap.tabIndex + '" class="tablinks">' + "New Tab " + stateMap.tabIndex + '</button>';
$("#tabs").append(tHtml);
console.log("we have a new tab!");
// add tab content section
var node = document.createElement('div');
node.setAttribute('id', 't' + stateMap.tabIndex);
node.className = "tabContent";
// load partial page place holder
var contentPlaceHolder = document.createElement('div');
contentPlaceHolder.setAttribute('id', 'c' + stateMap.tabIndex);
node.appendChild(contentPlaceHolder);
document.getElementById("content").appendChild(node);
console.log("we have new content placeholder for partial view!");
// HERE IS WHERE MY PROBLEM BEGINS !!!!!!
// NOTHING I DO WILL LOAD MY PARTIAL PAGE !!!!
//#{ Html.RenderPartial("MainContentPartial"); }
//$("#c" + stateMap.tabIndex).load('#{ Html.RenderPartial("MainContentPartial"); }');
//$("#c" + stateMap.tabIndex).load("GetView");
$(function () {
$("#c" + stateMap.tabIndex).load(
'<%= Url.Action("GetView", "MainViewController") %>'
);
})
//url: 'MainViewController/GetView',
//$.ajax({
// url: 'GetView',
// dataType: 'html',
// success: function (data) {
// $("#c" + stateMap.tabIndex).html(data);
// }
//});
}
JavaScript initModule
var initModule = function (data) {
stateMap.currentSection = data;
//Bind events
$("#TestLink").on("click", function (event) {
addTab(event);
});
$(document).ready(function () {
$(".tab").on("click", "button", function (event) {
openTab(event);
});
});
};
return { initModule: initModule };
My issue is with the last part of the JavaScript and probably the Controller. Can someone please tell me the correct way to load the partial view into my dynamically created tab content using JQuery?

You can load Partial View dynamically using Jquery in following way
$(document).on("click", "#TestLink", function () {
var url = "/MainView/GetView";
$.get(url, function (data) {
$("#content").html(data);
});
});
Here URL is the URL of action which will return PartialView.

Related

Collapse each div separately in C# MVC Razor foreach loop

I'm working on C# mvc project, and I'm trying to load product cart partial view, where I want in each row to have a button Read More for product specification. When users click on Read more it should collapse in div where specification for product are loaded.
I manage to accomplish this by creating css style for div Id - product-intro, but It functioning just on first row.
I'm now trying to dynamically create div Id's and also style inline product-intro"+"-"+i and I cant manage working.
Thanks in advance for any suggestions.
Here is my html:
#{int i = 0;}
#foreach (var line in Model.Lines)
{
var validQuantityClass = line.Quantity <= line.InStock ? "" : "danger";
<tr class="article #validQuantityClass" id="article-#line.Product.ProductId">
<td>
<div class="media">
<h4 class="group inner list-group-item-heading">#line.Product.Name</h4>
#{i++;}
<script>articleSpec()</script>
<div class="media-body">
<div id="#("product-intro"+"-"+i)" class="collapse" style="margin-bottom: 10px; border-bottom:1px solid #dee2e6; padding:10px 0; font-size: 12px;">
<div class="row justify-content-between">
<div class="col">
<span id='#string.Format("article-{0}-spec", line.Product.tecId)'></span>
</div>
</div>
</div>
<button type="button" class="btn btn-default" data-toggle="collapse" data-target="#product-intro-#i">Read More +</button>
</div>
</div>
</td>
</tr>
}
Javascript:
<script>
function articleSpec() {
$("#product-intro").each(function (index) {
var articleId = document.getElementById('tecId').value;
if (!articleId)
return;
var labelSelector = "#article-" + articleId + "-spec";
var url = "/Search/ArticleSpecification";
var postdata = "articleid=" + articleId;
$.post(url,
postdata,
function (data) {
$(labelSelector).html(data);
});
});
}
</script>
And this is my css for product-intro:
.cart-content #product-intro {
margin-bottom: 10px;
border-top: 1px solid #dee2e6;
border-bottom: 1px solid #dee2e6;
padding: 10px 0;
font-size: 12px;
}
I also tried to pass #i in javascript and dynamically load data in div:
function articleSpec(number) {
$("#product-intro" + '-' + number).each(function (index) {

jQuery css("display","table-cell") isn't immediately applied

<table style="border: none; margin-top: 40px; width: 100%;">
<tr>
<td id="adparser" style="width: 74.5%;"/>
<td id="thumbnailsSection" style="border: 2px solid black; display: none;">
<div style="text-align: center;">
<img src="arrow-right.png" style="border: 1px solid black; float: left; width: 16px; height: 16px;"/>
Identified Ads
</div>
<ol id="thumbnailsList" style="list-style-type: none;">
<div class="thumbnail">
<img src="https://s3.amazonaws.com/hiro-marketplace/thumb/413ce7c54ae87f9644b27a6d38790c2a.png"
style="width: 256px; height: 256px;"/><br/>
More Details<span><img src="play.png" style="width: 24px; height: 24px;"/></span>
</div>
<!-- More items... -->
</ol>
</td>
</tr>
</table>
Ok, so #thumbnailsSection starts with "display: none".
Later:
function requestChainsButtonClicked()
{
$.ajax(
{
type: "GET",
url: "json_simple.json" + queryString,
success: function(data,status,XMLHttpRequest)
{
if (($.isArray(data))&&(data.length>0)&&($.isPlainObject(
data[0])))
{
nodeID=0;
chartConfig.nodeStructure=buildTreeNode(data[0]);
}
new Treant(chartConfig);
$(".viewCell").click(viewThumbnailsClicked);
}
});
So when the user clicks a button, the content of the first table cell is built, and when the user clicks one of the .viewCell buttons (which are part of the tree in the first cell):
function viewThumbnailsClicked()
{
$.ajax(
{
type: "GET",
url: "thumbnails.json",
error: function(XMLHttpRequest,status,message)
{
$("#thumbnailsSection").css("display","none");
alert(status + ": " + message);
},
success: function(data,status,XMLHttpRequest)
{
var thumbnailsListSelector=$("#thumbnailsList");
thumbnailsListSelector.empty();
if ($.isArray(data))
{
for (var index=0;index<data.length;index++)
{
var thumbnailHTML="<div class=\"thumbnailItem\">";
thumbnailHTML+="<img class=\"thumbnail\" src=\"";
thumbnailHTML+=data[index].thumbUrl + "\"/><br/>";
thumbnailHTML+="More Details<span><img src=\"";
thumbnailHTML+="play.png\" class=\"details\"/>";
thumbnailHTML+="</span></div>";
thumbnailsListSelector.append(thumbnailHTML);
}
}
$("#thumbnailsSection").css("display","table-cell");
}
});
So, I would expect the second table cell (#thumbnailsSection) to appear immediately when I click the button, but it doesn't happen! Only after I click again the button that builds the first table cell, the second one is displayed.
What's actually the issue? Do I need to do some refresh on the table to see the second cell? Thanks.
Try It on ajax success but I am not sure
$("#thumbnailsSection").css("display","table-cell");
var thumbnailsListSelector=$("#thumbnailsList");
thumbnailsListSelector.empty();
if ($.isArray(data))
{
for (var index=0;index<data.length;index++)
{
var thumbnailHTML="<div class=\"thumbnailItem\">";
thumbnailHTML+="<img class=\"thumbnail\" src=\"";
thumbnailHTML+=data[index].thumbUrl + "\"/><br/>";
thumbnailHTML+="More Details<span><img src=\"";
thumbnailHTML+="play.png\" class=\"details\"/>";
thumbnailHTML+="</span></div>";
thumbnailsListSelector.append(thumbnailHTML);
}
}

Node Jquery load pages into div error

// Userlist data array for filling in info box
var userListData = [];
// DOM Ready =============================================================
$(document).ready(function() {
// Populate the user table on initial page load
populateTable();
// Username link click
$('#userList table tbody').on('click', 'td a.linkshowuser', showUserInfo);
// Add User button click
$('#btnAddUser').on('click', addUser);
// Delete User link click
$('#userList table tbody').on('click', 'td a.linkdeleteuser', deleteUser);
//Set Default page to Home.html
$('#content').load('views/home.html');
//Call navBar function
navBar();
projectBtn();
});
// Functions =============================================================
//Navbar function
function navBar() {
$('ul#navtest li a').click(function() {
var page = $(this).attr('title');
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});
}
function projectBtn() {
$('a.projectbutton').click(function() {
var page = $(this).attr('title');
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});
}
// Fill table with data
function populateTable() {
// Empty content string
var tableContent = '';
// jQuery AJAX call for JSON
$.getJSON( '/users/userlist', function( data ) {
// Stick our user data array into a userlist variable in the global object
userListData = data;
// For each item in our JSON, add a table row and cells to the content string
$.each(data, function(){
tableContent += '<tr>';
tableContent += '<td>' + this.username + '</td>';
tableContent += '<td>' + this.email + '</td>';
tableContent += '<td>delete</td>';
tableContent += '</tr>';
});
// Inject the whole content string into our existing HTML table
$('#userList table tbody').html(tableContent);
});
};
// Show User Info
function showUserInfo(event) {
// Prevent Link from Firing
event.preventDefault();
// Retrieve username from link rel attribute
var thisUserName = $(this).attr('rel');
// Get Index of object based on id value
var arrayPosition = userListData.map(function(arrayItem) { return arrayItem.username; }).indexOf(thisUserName);
// Get our User Object
var thisUserObject = userListData[arrayPosition];
//Populate Info Box
$('#userInfoName').text(thisUserObject.fullname);
$('#userInfoAge').text(thisUserObject.age);
$('#userInfoGender').text(thisUserObject.gender);
$('#userInfoLocation').text(thisUserObject.location);
};
// Add User
function addUser(event) {
event.preventDefault();
// Super basic validation - increase errorCount variable if any fields are blank
var errorCount = 0;
$('#addUser input').each(function(index, val) {
if($(this).val() === '') { errorCount++; }
});
// Check and make sure errorCount's still at zero
if(errorCount === 0) {
// If it is, compile all user info into one object
var newUser = {
'username': $('#addUser fieldset input#inputUserName').val(),
'email': $('#addUser fieldset input#inputUserEmail').val(),
'fullname': $('#addUser fieldset input#inputUserFullname').val(),
'age': $('#addUser fieldset input#inputUserAge').val(),
'location': $('#addUser fieldset input#inputUserLocation').val(),
'gender': $('#addUser fieldset input#inputUserGender').val()
}
// Use AJAX to post the object to our adduser service
$.ajax({
type: 'POST',
data: newUser,
url: '/users/adduser',
dataType: 'JSON'
}).done(function( response ) {
// Check for successful (blank) response
if (response.msg === '') {
// Clear the form inputs
$('#addUser fieldset input').val('');
// Update the table
populateTable();
}
else {
// If something goes wrong, alert the error message that our service returned
alert('Error: ' + response.msg);
}
});
}
else {
// If errorCount is more than 0, error out
alert('Please fill in all fields');
return false;
}
};
// Delete User
function deleteUser(event) {
event.preventDefault();
// Pop up a confirmation dialog
var confirmation = confirm('Are you sure you want to delete this user?');
// Check and make sure the user confirmed
if (confirmation === true) {
// If they did, do our delete
$.ajax({
type: 'DELETE',
url: '/users/deleteuser/' + $(this).attr('rel')
}).done(function( response ) {
// Check for a successful (blank) response
if (response.msg === '') {
}
else {
alert('Error: ' + response.msg);
}
// Update the table
populateTable();
});
}
else {
// If they said no to the confirm, do nothing
return false;
}
};
.border {
border: 4px solid black; }
.back2 {
background-color: #232323; }
.marginleft {
margin-left: 8%; }
.margin {
margin-right: 4%;
margin-left: 4%;
margin-top: 2%;
margin-bottom: 2%; }
.padding {
padding: 1%; }
.margintop {
margin-top: 1%; }
.margintop2 {
margin-top: 5%; }
.iconmargintop {
margin-top: 50px; }
.fill {
height: 100%;
width: 100%; }
p {
color: #ffffff; }
label {
color: #ffffff; }
h1 {
color: #ffffff; }
h2 {
color: #ffffff; }
th {
color: #ffffff; }
span {
color: #ffffff; }
h3 {
color: #ffffff; }
.projectseltext {
padding: 1%;
margin: 1%; }
.background {
background-color: #333333;
position: relative;
height: 100%; }
#blacktext {
color: black; }
.disablelink {
pointer-events: none;
cursor: default; }
.nav {
background-color: #b2b2b2; }
.nav a {
color: #ffffff;
font-size: 11px;
font-weight: bold;
padding: 14px 10px;
text-transform: uppercase; }
.nav li {
display: inline; }
.back1 {
background-color: #0c0c0c; }
.fit {
height: 100%;
width: 100%; }
.well {
background-color: #333333; }
.backg1 {
background-color: #333333; }
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<title></title>
</head>
<body>
<div id="project">
<div class="container-fluid row">
<a href="#" title="projectnew" class="projectbutton">
<div class="back2 col-md-11 margin border">
<img src="images/ph.jpg" class="thumbnail margin col-md-3" style="width:150px;" />
<h1 class="margin" style="margin-top:75px;">New Projects</h1>
</div>
</a>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<link rel="stylesheet" href="stylesheets/bootstrap.min.css" />
<link rel="stylesheet" href="stylesheets/main.css" />
<script src="build/js/jquery-2.2.4.min.js"></script>
<script src="build/js/bootstrap.min.js"></script>
<script src="build/js/global.js"></script>
<title></title>
</head>
<body class="background">
<div class="container-fluid nav navbar-inverse">
<ul id="navtest" class="margintop">
<li>
Home
</li>
<li>
Projects
</li>
<li>
Contact
</li>
<li>
Resume
</li>
<li>
About
</li>
<li>
Database
</li>
</ul>
</div>
<div id='content' class="tab-content" />
</body>
</html>
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<title></title>
</head>
<body>
<div id="projectnew">
<div class="row">
<div class="container col-md-12 margintop marginleft">
Back
</div>
<div class="container-fluid margin">
<a href="" data-toggle="tab">
<div class="back2 col-md-11 margin border">
<img src="images/ph.jpg" class="thumbnail margin" style="width:150px" />
<h1 class="margin">Comming soon.</h1>
</div>
</a>
</div>
</div>
</div>
</body>
</html>
This file is temporary, i know the contents wont do anything.
The function navBar works perfectly, however when trying to apply the same method to another class and div it seems to fail.
Whenever i click on the projectbutton class it redirects to error.html. For some reason the javascript is not seeing/handling the class on click and the href being an unsupported type redirects me to error.html. However i'm not sure what is wrong with my code.
welcome;
In your HTML code, <a href="projectnew" class="projectbutton"> you have an href for your a element, if you click on this, it will go to the page "www.yourdomain.com/projectnew" since this page does not exist, you will be redirected to your error page...
To solve this problem, you should use preventDefault, in order to prevent your link element to operate things that you do not want.
$('a.projectbutton').click(function(event) {
event.preventDefault();
var page = $(this).attr('href');
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});
I did not try it out, but it should work.
Read more about preventDefault: https://api.jquery.com/event.preventdefault/
OR;
Since the main problem is your href attributes in your a elements, try to remove them;
Home
Use title as your specifier in your JS;
$('a.projectbutton').click(function() {
var page = $(this).attr('title'); //changed this into title.
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});

Close toggle when clicking away from div

I have a calendar that opens up when the input is clicked, and it can be closed by a cross(X. I need the calendar to close when clicking anywhere else on the page. I have tried various methods on Stackoverflow but I think there are conflicts with the original scripts. I'm guessing there is something I can add to the closeClaendar function to close when outside of div?
function closeCalendar(calendarId) {
$("#" + calendarId).hide();
}
function CalendarMonthChanged(contract, product, dropdtls, form, ticketType, dateselectorid) {
$calendar = $("#CalendarWrapper");
var loader = '<%= Html.StaticImage(Url, "ajax-loader.gif") %>';
$calendar.find(".table").html("<div class = 'calendar-loading' style='width:175px;'><img src = '" + loader + "' /></div>");
var qty = 2;
var dataArray = {
contract: contract,
productId: product,
dropdtls: dropdtls,
formNumber: form,
ticketType: ticketType,
numTickets: qty,
dateSelectorId: dateselectorid
};
$.ajax({
type: "POST",
url: '<%= Url.Action("Calendar", "productapi", null) %>',
data: dataArray,
success: function (response) {
$calendar.html(response);
toggleLayer("CalendarForm1");
}
});
}
<div id="CalendarWrapper">
<div id="Allocation">
<div id="CalendarForm1" class = "CalendarForm" style="display:none;">
<div class="allocation_form bg">
<div class="calendar_header">
<a href="javascript:closeCalendar('CalendarForm1');">
<span class="m-xs-10 halflings remove red"></span>
</a>
<select name="calendar_month" class="form-control" onchange="CalendarMonthChanged('<%= Model.ContractID %>','<%= Model.AWItemId %>',this.value,'<%= Model.FormNumber %>', '<%= Model.TicketType %>', <%= (int)Model.DateSelector %>); ">
<%= Model.Months %>
</select>
</div>
<div id="Loading" class="Loading" style="width:175px;height:172px;display:none;"></div>
<%= Model.Days %>
</div>
</div>
</div>
</div>
Here is one easy way by adding a click handler to document.
jsFiddle: http://jsfiddle.net/6pcq7pvo/3/
$(document).on("click", function (e) {
if ($("#calendar").is(":visible") && !$(event.target).is('#calendar *, #calendar')) {
// user clicked somewhere in the document but not inside the calendar
$("#calendar").hide();
$("#btnOpenCalendar").show();
} else if (event.target.id === "btnOpenCalendar") {
// user clicked the "Show calendar" button
$("#btnOpenCalendar").hide();
$("#calendar").show();
}
else if ($(event.target).is('#calendar span'))
{
// user clicked a date in the calendar
// for demo purposes only; normally your calendar plugin handles this for you
alert("Clicked date: " + $(event.target).text());
}
});
#calendar {
height: 100px;
width: 100px;
border: 1px solid black;
background-color: #ccc;
display: block;
overflow: hidden;
}
#calendar span {
display: inline-block;
width: 17px;
border:1px solid #ddd;
cursor: pointer;
}
#btnOpenCalendar { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>click anywhere in this frame, but outside of the "calendar" (gray box) to close calendar</h3>
<div id='calendar'><span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span>10</span>
</div>
<input id='btnOpenCalendar' type='button' value='Show calendar' />
Try this:
$(document).click(function(){
if($("#" + calendarId).is(':visible')){
$("#" + calendarId).hide().css("visibility", "hidden");;
}
});
also on your anchor click do, following to avoid hiding the calendar again:
$(document).on('click', 'a', function (e) {
//show calendar
$("#" + calendarId).show()
e.stopPropagation();
});
or instead of e.stopPropagation(); you can also use e.preventDefault();

jQuery/Javascript : How to prepend elements without going back to the top of last prepended element?

Whenever I click prepend, after all elements are prepended, the view of the chat area switches to the top of the chat area or the last prepended element. This is different from append, whereby after all elements are appended, the view of the chat area does not switch to the end of the chat area or last appended element but still stays at its previous position.
How do I make the prepend function act in the same way as append in the sense that the view of the chat area does not change similar to FB's load previous message function?
Here is a sample code that illustrates what I mean.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
<style type="text/css">
.chatbox{
border:1px solid #2a6496;
height: 600px;
margin-top:50px;
}
.chatbox div{
height: 100%;
}
.rightP{
border-left: 1px solid #2a6496;
}
.rightP .contents{
border-bottom: 1px solid #2a6496;
height: 70%;
}
.rightP .send{
padding : 5% 5% 5% 5%;
height: 30%;
}
#response{
height: 200px;
overflow-y: scroll;
overflow-wrap: break-word;
}
</style>
<script>
function appendMessage()
{
var data = 'hello';
var message = document.createElement('p');
message.innerHTML = data;
console.log(message.innerHTML);
$('#response').append(message);
$('#response').append($('.load'));
}
function prependMessage()
{
for(var $i = 0;$i<10;$i++)
{
var data = 'hello'+$i;
var message = document.createElement('p');
message.innerHTML = data;
console.log(message.innerHTML);
$('#response').prepend(message);
$('#response').prepend($('.load2'));
}
}
</script>
<body>
<div class="container">
<div class="chatbox">
<div class="col-sm-8 rightP">
<div class="row contents">
<div class="row msg">
<div id="response" class="msg form-group">
<a onclick="return appendMessage()" class="load btn btn-default">Append</a>
<a onclick="return prependMessage()" class="load2 btn btn-default">Prepend</a>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
In HTML there should be return in your onlick:
<a onclick="return loadMessage();" class="load btn btn-default">Load More Msg</a>
In JS you need to add return false to your function loadMessage.
var loadMessage = function(){
var firstMessage = $messagesWrapper.find('> p:nth-child(2)');
$.ajax({
....
if(messages.length<10){
$('.load').hide();//hide the load button if remaining messages to load is <10
}
success: function(messages){
$.each(messages, function() {
prependMessage(this);
});
},
....
});
return false;
};
Try this:
<div id="response" class="msg form-group">
<a onclick="loadMessage(); return false;" class="load btn btn-default">Load More Msg</a>
</div>
If this doesn't work, try another way:
var loadMessage = function(){
e.preventDefault(); // preventing any scroll action
var firstMessage = $messagesWrapper.find('> p:nth-child(2)');
(...)
And
var prependMessage = function(data){
e.preventDefault(); // preventing any scroll action
var message = document.createElement('p');
(...)
If this doesn't work please provide the whole code so we can reproduce.

Categories

Resources