how to auto scroll down in div on content added? - php

I am developing a chat program using jquery, php and ajax. and my problem is that when user puts msgs and when the chat box is overflowed it should auto scroll down when new msg enter and chat box overflowed. What I tried to achieve is this.
CODE
$.ajaxSetup ({
cache: false
});
$(document).ready(function(e) {
setInterval (function() {
$('.main').load('display_messages.php');
},1000)
$(function() {
//Function for press Return button
$('#newMessageContent').keypress(function(e) {
if (event.keyCode == 13 || !event.keyCode == all ) {
setTimeout (function() {
$('.main').load('display_messages.php');
setTimeout (function() {
$('.main p:last').addClass('animated fadeIn');
},20)
},50);
//$('.main').stop().animate({scrollTop:$('.main')[0].scrollHeight}, 1000);
}
});
// Functions for click button
$('#newMessageSend').click(function() {
setTimeout (function() {
$('.main').load('display_messages.php');
setTimeout (function() {
$('.main p:last').addClass('animated fadeIn');
},20)
},50);
//$('.main').stop().animate({scrollTop:$('.main')[0].scrollHeight}, 1000);
});
var chckIt = setInterval(function(){
$('.main').one('DOMSubtreeModified',function(){
setTimeout(function() {
$('.main').stop().animate({scrollTop:$('.main')[0].scrollHeight}, 1000);
},500);
})
},1000)
$('.main').on('scroll',function(){
if ( $('.main').scrollTop() === 0 ){
clearInterval(chckIt);
}
});
});
});
it has some bugs. it will auto scroll down but it repeat itself again and again and not stoping, and you cant scroll up to see older msgs if u want.
so then I used this function $('.main').on('scroll',function(){
if ( $('.main').scrollTop() === 0 ){
clearInterval(chckIt);
}
}); to control it but its useless.
here is html.
code
<div class="chatBox">
<div class="chatlogo">
<embed src="test2.swf" play="true" class="vid2" loop="true" width="180" height="50" salign="C" scale="ShowAll" id="vid_2" quality="High" wmode="transparent" name="vid_2" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash">
</div>
<div class="user">
<form name="signIn" id="signInForm" action="signout_delete_content.php" method="post" onSubmit="return false">
<span class="error animated">Invalid uername</span>
<input name="username" type="text" id="username" placeholder="Enter username" size="13px" onClick='document.username.value = "" '>
<input type="submit" id="signIn" value="SING IN">
</form>
<span class="welcome"></span>
<input type="button" id="signOut" value="SIGN OUT" onclick="window.location.reload();">
</div>
<div class="main">
<p>Admistrator: Hello msgs here.</p>
</div>
<div class="messageBox">
<form name="messageBoxSignInForm" id="messageBoxSignInForm" onSubmit="return false">
<input type="submit" id="messageBoxSignIn" value="Sign In to Enter Chat">
</form>
<form name="newMessage" class="newMessage" action="" onSubmit="return false">
<textarea name="newMessageContent" id="newMessageContent" placeholder="Enter your message here.">Enter your message here</textarea>
<input type="submit" id="newMessageSend" value="Send">
</form>
</div>
</div>
any help would be appreciated. thanks

You can't scroll up because you keep triggering load('display_message.php'), which will trigger 'DOMSubtreeModified' event. So, you can't rely on 'DOMSubtreeModified' and have to check for a new message by other means. For example, you may count the number of messages for each 'display_message.php' and check for difference.
var old = 0, new = 0;
$('#newMessageSend').click(function() {
setTimeout (function() {
$('.main').load('display_messages.php', chckIt);
setTimeout (function() {
$('.main p:last').addClass('animated fadeIn');
},20)
},50);
//$('.main').stop().animate({scrollTop:$('.main')[0].scrollHeight}, 1000);
});
var chckIt = function(){
new = $('.main').children().length;
if (new > old)
{
old = new;
setTimeout(function() {
$('.main').stop().animate({scrollTop:$('.main')[0].scrollHeight}, 1000);
},500);
}
};

You were right,my previous answer doesn't works..
$('.messageBox').scrollTop($('.messageBox')[0].scrollHeight)
this works well:
jsfiddle:
http://jsfiddle.net/Lh4TN/6/

Related

Cannot pass textarea input to a PHP variable

To begin, I'm working with 3 languages. HTML, Javascript and PHP. I'm unable to pass user inputted textarea text to a PHP variable which would be used as a message in an email that would be sent out. What I believe to be the problem is that my textarea is actually in a modal window and for some reason I think that is what is screwing things up.
Here is my HTML Code:
<form name="rejectForm" action="">
<div class="rejectModal" title="rejectModal" id="rejectModal" style="display: none; padding:15px ">
<b> Text in the modal window</b>
<center>
<textarea id="rejectArea" name="rejectArea" value="{$rejectAreaNote}" rows="6" cols="43"/> </textarea>
</center>
<br/>
<center>
<input type="button" value="Reject" class="btn success id="submitReject"" id="btnRejectDocumentModal" name="Reject" />
<input class="btn" type="reset" value="Cancel" id="btnCancelSaveModal" />
</center><br/><br/>
</div>
</form>
</div>
JS Code:
$(function() {
$(".submitReject").click(function() {
// validate and process form here
$('.error').hide();
var rejectAreaNote = $("textarea#rejectArea").val();
var noteLength = rejectAreaNote.length;
if (rejectAreaNote == "" || noteLength < 5) {
$("label#rejectArea_error").show();
$("textarea#rejectArea").focus();
return false;
}
var dataString = rejectAreaNote;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "gs_ViewDocument.php",
data: dataString,
success: function() {
$('#reject_form').html("<div id='message'></div>");
$('#message').html("Reject Form Submitted!");
}
});
return false;
});
});
What creates the Modal (JS):
$('.rejectModal').css("background", "lightblue");
$('#btnRejectDocument').bind(isTouchScreen ? "touchstart" : "click", function(){
if (!gsSelection.unselectElem()) return false;
$('.rejectModal').dialog({
modal:true,
resizable:false,
width: 400,
}).removeClass("ui-widget-content");
$(".ui-dialog-titlebar").hide();
return;
});
$('#btnRejectDocumentModal').bind(isTouchScreen ? "touchstart" : "click", function(){
$(this).parents('div.rejectModal').dialog('close');
});
$('#btnCancelSaveModal').bind(isTouchScreen ? "touchstart" : "click", function(){
$(this).parents('div.rejectModal').dialog('close');
});
PHP Code:
if(isset($_POST['Reject'])&&$_POST['Reject']=='Reject')
{
$isReject = true;
RejectAction($DocumentID, $ClientName, $ClientEmail);
$smartyvalues["isReject"] = $isReject;
$smartyvalues["RejectMsg"] = "The document invitation was successfully rejected!";
}
Any help is greatly appreciated.
Try the below is should fix it :
<textarea id="rejectArea" name="rejectArea" rows="6" cols="43"> {$rejectAreaNote}</textarea>
you were closing your textarea tag twice /> and then </textarea>
<input type="button" value="Reject" class="btn success id="submitReject"" id="btnRejectDocumentModal" name="Reject" />
The closing quotes here are wrong (Two quotes after submitReject).

Javascript Automated Click?

I have the following function for a jquery login form and want to run it when php detects that the user is not logged in by echoing a javascript function that clicks the login button automatically
jq Code:
<script type="text/javascript">
$(document).ready(function() {
$('a.login-window, a.log').click(function() {
//Getting the variable's value from a link
var loginBox = $(this).attr('href');
//Fade in the Popup
$(loginBox).fadeIn(300);
//Set the center alignment padding + border see css style
var popMargTop = ($(loginBox).height() + 24) / 2;
var popMargLeft = ($(loginBox).width() + 24) / 2;
$(loginBox).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
// Add the mask to body
$('body').append('<div id="mask"></div>');
$('#mask').fadeIn(300);
return false;
});
// When clicking on the button close or the mask layer the popup closed
$('a.close, #mask').live('click', function() {
$('#mask , .login-popup').fadeOut(300 , function() {
$('#mask').remove();
});
return false;
});
});
</script>
HTML
<div id="login-box" class="login-popup">
<img src="close_pop.png" class="btn_close" title="Close Window" alt="Close" />
<form method="post" method="post" name="f" id="f" class="signin" action="login.php">
<fieldset class="textbox">
<label class="username">
<span>Username or email</span>
<input id="username" name="username" value="" type="text" autocomplete="on" placeholder="Username">
</label>
<label class="password">
<span>Password</span>
<input id="password" name="password" value="" type="password" placeholder="Password">
</label>
<button class="submit button" type="submit" name="Submit" value="<?php echo $lang['LOGIN'];" style="background:none;">Sign in</button>
<p>
<a class="forgot" href="#">Forgot your password?</a>
</p>
</fieldset>
</form>
</div>
if you want to auto click a button, you are looking for .trigger
$('#some-id').trigger('click');
.trigger( 'event' ) explanation:
Execute all handlers and behaviors attached to the matched elements
for the given event type.
(as you are already using jQuery, hence)
<?php
if (!$lang['LOGIN']) {
echo '<script type="text/javascript">';
echo '$(function() {';
echo '$("a.login-window, a.log").trigger("click")';
echo '});';
echo '</script>';
}
?>
var loggedIn = isUserLoggedIn(); // check login status
if(!loggedIn){
$('a.login-window, a.log').trigger('click');
}
.trigger Docs

delay submit on form by 5 seconds and display jquery dialogue?

i need some help please. I am trying to delay the the submission of a form by 5 seconds so a jquery dialogue loading box appears before submitting the login form.
At the moment the code im using does delay the submit however it stops the form from submitting the data and wont log the user in.
I'm pretty sure its because im using e.preventDefault in my javascript however it doesnt work without it, can anyone please show me how i can delay the form from submitting and submit the data successfully so it does log the user in.
Thanks.
<div id="login">
<?php
if (!logged_in()) {
?>
<form id="myform" form action="login.php" rel="shadowbox" method="post" class="loginform">
Email
<input type="text" name="email" maxlength="30" />
Password
<input type="password" name="password" maxlength="30" />
<input type="image" src="../PTB1/assets/img/icons/loginarrow1.png" name="submit" class="loginbutton" value="Login" />
</form>
<?php
}
if (logged_in()) {
?>
Logged in as, <?php echo $_SESSION['email'] ?>. Dashboard, Logout | <div class="login_settings" id="login_settings"></div>
<?php
}
?></div>
<script>
$('#myform').submit(function (e) {
var form = this;
e.preventDefault();
setTimeout(function () {
form.submit();
}, 3000); // in milliseconds
});
</script>
<script>
$(document).ready(function() {
$('#myform').submit(function() {Shadowbox.open({
content: '<iframe src="login.php" width="500" height="300" scrolling="no" style="overflow:hidden; border:none;"></iframe>',
player: "html",
height: 300,
width: 500
});
});
});
</script>
Use single submit handler. I tried this on my local system and it works.
<script type="text/javascript">
$(document).ready(function() {
$('#myform').submit(function(e) {
var form = this;
e.preventDefault();
Shadowbox.open({
content: '<iframe src="login.php" width="500" height="300" scrolling="no" style="overflow:hidden; border:none;"></iframe>',
player: "html",
height: 300,
width: 500
});
setTimeout(function () {
form.submit();
}, 3000); // in milliseconds
});
});
</script>

Jquery for submiting without refresh (no validation required)

I have a form for Tags that is working OK, with some server validation, I would like to add a Jquery to submit the content without refreshing:
<form method="post" action="tags">
<div>
<input type="hidden" name="id" value="getId()" />
<input type="text" name="tag" />
<input type="submit" value="Add" name="add" />
</div>
</form>
Any advice will be highly appreciated.
Check out the jQuery Form Plugin. Using it, you can submit a form without reloading the page like so:
<form id="aForm" action="target.php" method="post>
...
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#aForm").ajaxForm();
});
</script>
The ajaxForm() function also supports all options (such as a callback function) that can be passed to the standard jQuery $.ajax function.
$(document).ready(function() {
$(form).submit( function() { // could use $(#submit).on('click', function(){ as well
$.ajax({
url: 'yourposturl',
data: $(form).serialize(),
Success: function() {
alert('ok');
}
}); //end ajax
return false;
}); //end submit()
});
Should take all form vars , serialize them so the server can receive, the return false is so page doesnt refresh on submit (stops propagation and default)
Add the JQuery javascript library
Turn the submit into a button
<button id="submitbutton" >Add</button>
Add ids to your inputs
<input type="text" id="tag" name="tag" />
And add the jquery to the click for the button ...
<script type="text/javascript">
$(document).ready(function() {
$("#submitbutton").button().click(function(){
$.post("tags.php",{id: $("#id").val(), tag: $("#tag").val()});
});
});
</script>
<form method="post" action="tags">
<div>
<input type="hidden" name="id" value="getId()" />
<input type="text" name="tag" />
<input class="button" type="button" value="Add" name="add" />
</div>
</form>
$(function(){
$('.button').click(function(){
var data = $('form').serializeToObject();
$.post('tags.php', data);
});
});
// jQuery Extension to serialize a selector's elements to an object
$.fn.serializeToObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};

Run jQuery modal dialog if PHP returns 0

I need to run jQuery modal dialog if mainOptim.php returns 0. Now Firebug says $dialog is not defined. What should I change in the code?
<script type="text/javascript">
$(document).ready(function() {
var $dialog = $('<div></div>')
.html('This dialog will show every time!')
.dialog({
autoOpen: false,
title: 'Basic Dialog'
});
});
function click_function_ps() {
$.ajax({
url: 'callpage.php?page=optim/mainOptim.php',
data: 'earl='+$('#earl').val(),
success: function(html,msg){
if(msg === '1'){
$('#opt_container').html(html);
} else {
$dialog.dialog('open');
return false;
}
}
});
}
</script>
<div id="fragment-2">
<table width="100%">
<tr>
<td width="100%">
<form name="optform" method="post" action="#">
<div class = "boxx">
<label for="earl"><span>Parameter:</span></label>
<input type="text" class="input-text" value="5" size="11" maxlength="11" name="earl" id="earl">
</div>
<br/>
<div class="buttons">
<a href="#" class="regular" onclick="click_function_ps();">
<img src="images/opt.png" alt=""/> Run
</a>
</div>
</form>
</td>
</tr>
</table>
</div>
That's because you declared it as a local variable using the var keyword in the ready scope.
Remove the var in front of the declaration (var $dialog).

Categories