Hi I'm doing a chat script that I've gotten somewhere that needs quite modifications. The function I need to achieve is after successful loading of user to chat with the view should go to bottom directly. I have done things which failed on several occasions, it does automate to bottom but when I tried scrolling the content it still goes back to bottom which should not happen.
This is what I have so far.
<?php
$ctr = 0;
if (is_array($buddies)) {
foreach ($buddies as $buddy) {
?>
<span style="float: right;"><?php echo $buddy->unreadMsgCtr; ?></span>
<b><?php echo humanize($buddy->fullName) ?></b> <br />
<?php
++$ctr;
}
}
?>
<script type="text/javascript">
$(document).ready(function() {
<?php for ($ctrjs = 0; $ctrjs < $ctr; $ctrjs++) {?>
$('#friend' + <?php echo $ctrjs; ?>).live('click', function() {
$('#buddies').hide();
var chattingWith = $(this).attr('chattingID');
startrefresh();
$('#chatroom').show();
$('#chatmessage').html('<img src="<?php echo site_url('/images/ajax-loader.gif');?>" width="16" height="16" />');
$.post("<?php echo site_url('chats/chatbuddy');?>",{
username: $("#friend"+<?php echo $ctrjs; ?>).html(),
recipientID: chattingWith
});
});
<?php } ?>
});
</script>
//chats.php when a particular buddy has been clicked.
<script type="text/javascript">
var autoScrollEnabled = true;
$(document).ready(function() {
toggleAutoScroll();
if(autoScrollEnabled == true) {
$(".messages").animate({ scrollTop: $('.messages')[0].scrollHeight}, 1000);
//return false;
toggleAutoScroll();
}
function toggleAutoScroll() {
autoScrollEnabled = !autoScrollEnabled; //! reverses the value, true becomes false, false becomes true
if (autoScrollEnabled == true) { //scroll down immediately if a.s. is reenabled
$(".messages").animate({ scrollTop: $('.messages')[0].scrollHeight}, 9999999999);
}
}
$('#closechat').live('click', function() {
$('#chatroom').hide();
//scrolled = 0;
stoprefresh();
});
});
</script>
<div class="headerchat" style="width: 217px;"><div class="buddycontainer"> Chatting</div>
<div class="closecontainer">✖ </div>
<br class="breaker" />
</div>
<?php
if (is_array($chat)) {
foreach ($chat as $item){ ?>
<div class="conversation" style="width: 215px;">
<b><span class="username"><?php echo $item['username']; ?></span></b>
<span class="gray" style="float: right;" title="<?php echo date('M d, Y g:i A', $item['time']);?>"> <?php echo date('g:i A', $item['time']);?></span>
<br /><?php echo $item['message']; ?>
</div>
<?php } ?>
<?php }?>
BTW here is the jsfiddle I don't understand it's working properly in jsfiddle. http://jsfiddle.net/STQnH/3/
I'm not sure if I am heading on the right track. I just want to achieve that. Thank you guys.
Try wrapping your code in:
$(document).ready(function(){ //your code here
});
or
$( window ).load(function() {//your code here
});
If it works in jsFiddle but not on the live site this is likely what's missing. jsFiddle adds it for you. You can change this option in the drop down menu indicated by my freehand circle.
jQuery faq for $(document).ready()
Related
I have one index.php page, whose content changes whether you activated a session or are logged out.
When users are logged in, a click on the link "showhide" should show the class "users".
When users are logged out the link "showhide" is hidden and instead the link "showhide2" is visible, which should show the class "users2" when its pressed.
I found a jQuery-snippet online that does exactly this and works fine for the link "showhide"
Unfortunately it doesn't work for the link "showhide2" - the class is always visible...
Here's my code:
<div id="content" style="margin-top:10px;height:100%;">
<?php
/*echo "Der Nutzername ist ".$_SESSION['user'];
echo "<br>Die Session lautet ".$_SESSION['sessionname'];
echo "<br>".session_id();*/
$sArray = explode(".",$_SESSION['sessionname']);
$session1 = $sArray[0];
$session2 = $sArray[1];
$sessionausblenden = $_SESSION['sessionname'];
if (!isset($sessionausblenden)){
echo "<style type='text/css'>
#showhide{
visibility:hidden !important;
}
.users{
visibility:hidden !important;
}
#logout {
visibility:hidden !important;
}
</style>";
}
elseif (isset($sessionausblenden)){
echo "<style type='text/css'>
#showhide2{
visibility:hidden !important;
}
.users2{
visibility:hidden !important;
}
</style>";
}
?>
<a id="showhide" href="#" style="background:#<?php echo $session2?>;">+</a>
<a id="showhide2" href="#" style="background:#<?php echo $session2?>;">?</a>
<a id="logout" onclick="return confirm('Are you sure?')" href="logout.php">-</a>
<script type="text/javascript">
$(document).ready(function () {
$('.users').hide();
$('a#showhide').click(function () {
$('.users').toggle(400);
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$('.users2').hide();
$('a#showhide2').click(function () {
$('.users2').toggle(400);
});
});
</script>
<center><h1>Group Chat In PHP</h1></center>
<div class="chat">
<div class="users" style="background-color:#<?php echo $session2?>;">
<?php include("users.php");?>
</div>
<div class="users2" style="background-color:#<?php echo $session2?>;">
<?php include("users.php");?>
</div>
<div class="chatbox">
<?php
if(isset($_SESSION['user'])){
include("chatbox.php");
}else{
$display_case=true;
include("login.php");
}
?>
</div>
</div>
</div>
You can see the live-version here: http://team3.digital-cultures.net/index.php
Just enter a name of your choice and choose an option from "Start" and "Ziel" and your session is started (and a chat is opened).
Can you help me finding the mistake?
Thanks!
It seems an event is not being bound to #showhide2. If you listen at the document level and let it bubble to #showhide as the target, it may work. This can happen for dynamically loaded elements.
Change
$(document).ready(function () {
$('.users2').hide();
$('a#showhide2').click(function () {
$('.users2').toggle(400);
});
});
To
$(document).ready(function () {
$('.users2').hide();
$(document).on('click','#showhide2',function () {
$('.users2').toggle(400);
});
});
Most importantly, please resolve this error:
$(".msgs").animate({scrollTop:$(".msgs")[0].scrollHeight}); on line 2 of chat.js $(".msgs")[0] is undefined.
There are no elements matching $('.msgs'). Wrap it with the following:
if($('.msgs').length) {
$(".msgs").animate({scrollTop:$(".msgs")[0].scrollHeight});
}
This maybe why the event isn't getting bound.
The header.php has a <div id="content"></div> and then will load the page user.php
Q1: Is javascript coding on the header.php can not interact with the loaded content?
Therefore I put the js code on the loaded page, but i found a little bit strange.
Q2:
The paging function is working, suppose it is on page 4.
After I editting one of the row, the page go back to first page. I want to keep it on page 4.
< 1 2 3 4 5 6>
I want to store the current link as a text within a after i click the paging, however the link is stored first and then page will refresh and clear the data.
The href of the paging links will look like
localhost://blog/index.php/admin/users/show/10
localhost://blog/index.php/admin/users/show/20
localhost://blog/index.php/admin/users/show/30
Please point out the solution or suggest another better solution
$("input[name=submit]").click(function() {
$(this).parents('.alert-box').hide();
$form = $(this).parent('form');
$.post(
$form.attr('action'),
$form.find(':input').serializeArray(),
function(data) {
$("#content").html(data);
}
);
});
View:header.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link href="<?= $css; ?>bootstrap.css" rel="stylesheet" type="text/css">
<link href="<?= $css; ?>basic/basic.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="<?= $js; ?>jquery.js"></script>
<script type="text/javascript" src="<?= $js; ?>jquery_validate.js"></script>
<script type="text/javascript" src="<?= $js; ?>form_control.js"></script>
<script type="text/javascript" src="<?= $js; ?>additional-methods.min.js"></script>
</head>
<body>
<style>
#content{
background-color: #D0D0D0;
float:left;
width:80%;
}
#main-frame{
width:100%;
}
#list{
width:18%;
float:left;
}
#delete-alert-box{
background-color: #269abc;
position: absolute;
z-index: 99999;
display: none;
}
#edit-alert-box{
background-color: #269abc;
position: absolute;
z-index: 99999;
display: none;
}
body{
font-size:2em;
}
</style>
<script language="javascript">
$(document).ready(function() {
init();
$('.open').click(function(e) {
e.preventDefault();
$.post($(this).attr('href'), function(data) {
$('#content').html(data);
});
});
});
function init() {
$.post(
"<?php echo site_url("admin/users/show");?>", function(data) {
$("#content").html(data);
}
);
}
</script>
<div id="header">
<div id="logo">
</div>
<?php if ($this->AuthModel->check_admin_log()) { ?>
Logout
<?php }
?>
</div>
<ul id="list">
<li>
Users Manage
</li>
<li>
Group Manage
</li>
<li>
Post Mange
</li>
<li>
System Setting
</li>
<li>
<a href="<?php echo site_url('logout/admin') ?>" >Logout</a>
</li>
</ul>
<div id="content" class="box"></div>
view:users.php
<table border="1">
<tr><th>User Id</th><th>User Name</th><th>Email</th><th>Registeration Date</th><th>Group</th><th>State</th><th>Operation</th></tr>
<?php foreach ($users as $user): ?>
<tr>
<td><?= $user->id; ?></td>
<td><?= $user->username; ?></td>
<td><?= $user->email; ?></td>
<td><?= mdate('%Y-%m-%d', $user->registeration_time); ?></td>
<td><?= $user->user_type; ?></td>
<td><?= $user->account_status; ?></td>
<td>
<button type="button" value="<?php echo $user->id; ?>" name="delete">X</button>
<button type="button" value="<?php echo $user->id; ?>" name="edit">edit</button>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php echo $links ?>
<div id="delete-alert-box" class="alert-box">
<div class="cancel">X</div>
<h3>Are you sure to delete the account?</h3>
<form action="<?php echo site_url('admin/users/delete') ?>" id="deleteForm">
<input type="hidden" value="" name="user_id">
<input type="button" value="Yes" name="submit">
<input type="button" value="No" name="cancel">
</form>
</div>
<div id="edit-alert-box" class="alert-box">
<div class="cancel">X</div>
<h3>Edit User:<span id="username"></span></h3>
<form action="<?php echo site_url('admin/users/edit') ?>" id="editForm">
<table>
<tr>
<td>Group</td>
<td>
<select name="group" id="group">
<option value="1">Nomal User</option>
<option value="2">Amin</option>
</select>
</td>
</tr>
<tr>
<td>State</td>
<td>
<select name="state" id="state">
<option value="1">Activated</option>
<option value="2">Non-Activated</option>
<option value="3">Blocked</option>
</select>
</td>
</tr>
</table>
<input type="hidden" value="" name="user_id">
<input type="button" value="Yes" name="submit">
<input type="button" value="No" name="cancel">
</form>
</div>
<script>
$(document).ready(function() {
$(".cancel").click(function() {
$(this).parent('.alert-box').hide();
});
$("input[name=cancel]").click(function() {
$(this).parents('.alert-box').hide();
});
$("button[name=delete]").click(function() {
var $user_id = $(this).attr('value');
if ($user_id !=<?php echo $this->session->userdata('user_id') ?>) {
$("#delete-alert-box").show();
$('#delete-alert-box').find('input[type=hidden]').attr('value', $user_id);
}
});
$("button[name=edit]").click(function() {
var $user_id = $(this).attr('value');
if ($user_id !=<?php echo $this->session->userdata('user_id') ?>) {
$("#edit-alert-box").show();
var $tr = $(this).parents('tr');
var $tds = $tr.find('td');
$('#edit-alert-box').find('input[type=hidden]').attr('value', $user_id);
$('#group').find('option').each(function(index) {
$(this).removeAttr('selected');
});
$('#group').find("option[value=" + get_group_code($($tds[4]).html()) + "]").attr('selected', 'selected');
$('#state').find("option[value=" + get_account_code($($tds[5]).html()) + "]").attr('selected', 'selected');
}
});
$("input[name=submit]").click(function() {
$(this).parents('.alert-box').hide();
$form = $(this).parent('form');
$.post(
$form.attr('action'),
$form.find(':input').serializeArray(),
function(data) {
$("#content").html(data);
}
);
});
$('.paging a').click(function(e) {
e.preventDefault();
$.post($(this).attr("href"), function(data) {
$("#content").html(data);
});
});
});
function get_group_code(name) {
switch (name) {
case "Normal User":
return 1;
case "Admin":
return 2;
}
}
function get_account_code(name) {
switch (name) {
case "Activated":
return 1;
case "Non-Activated":
return 2;
case "Blocked":
return 3;
}
}
</script>
Controller: admin/users.php
function pagination() {
$this->load->library('pagination');
$config['base_url'] = site_url('admin/users/show');
$config['total_rows'] = $this->UsersModel->get_num_rows();
$config['per_page'] = '10';
$config['uri_segment'] = 4;
$config['full_tag_open'] = '<p class="paging">';
$config['full_tag_close'] = '</p>';
$this->pagination->initialize($config);
return $this->pagination->create_links();
}
public function show() {
$data['users'] = $this->UsersModel->get_users(10, $this->uri->segment(4, 0));
$data['links'] = $this->pagination();
$this->load->view('admin/users', $data);
}
public function delete() {
$user_id = $this->input->post('user_id');
if (!$this->UsersModel->delete_user($user_id)) {
echo "Unknown error";
}
$this->show();
}
public function edit() {
$user_id = $this->input->post('user_id');
$state = $this->input->post('state');
$group = $this->input->post('group');
$data = array(
'id' => $user_id,
'account_status_code' => $state,
'group_status_code' => $group
);
if (!$this->UsersModel->edit_user($data)) {
echo "Unknown error";
}
$this->show();
}
The paging function is working, suppose it is on page 4. After I
editting one of the row, the page go back to first page. I want to
keep it on page 4.
When opening that 4-th page in a browser, you can save its number in session and then after editing you can read that value you stored in session i.e - 4.
#session_start();
function indexAction()
{
$_SESSION['curr_page'] = 4; // or take it from $_GET
}
function saveAction(){
// .... do stuff....
header('location: page.php?page=' . $_SESSION['curr_page']);
}
first the best way to do paging is via get, to get the url friendly and rotating the User in case it needs to pass it on.
you need set data in console.log(), for view if data this value,
if the expected values are coming up to the date, try switching by append html:
example.
$ ("# content") html ('.');
$ ("# content") append (date).;
So I have a table where each cell is a name of a game and when you click it it needs to show in a fancybox the results of the user which clicked the cell (I use table Indexes to get the GameID and the Session variable to get userID) which will be used to load the results from a second PHP page.
If I click on a cell for the first time the fancybox will not display anything and after I close fancybox and click on any cell again it works fine. Am I doing something wrong?
This is the whole javascript:
$(".jogos").fancybox({
'hideOnContentClick': true,
'onComplete':function(element)
{
var gameIdx = $(element).index();
var cateIdx = $(element).parent().parent().index();
var gameIdxPHP;
var catIdxPHP;
var gameID;
var userId = '<?php echo $_SESSION['userID']; ?>'
<?php
for ($i=1; $i<= count($categoryArray);$i++)
{
for ($j=1; $j<=count($categoryArray[$i-1]->gamelist);$j++)
{
?>
catIdxPHP = '<?php echo $i ?>' -1;
gameIdxPHP = '<?php echo $j ?>' -1;
if (catIdxPHP == cateIdx && gameIdxPHP == gameIdx)
{
gameID = '<?php echo $categoryArray[$i-1]->gamelist[$j-1]->GameID; ?>';
$("#graphic").load("backoffice/resUserNivel2short.php", {userId:userId,gameID:gameID}, function(){ });
}
<?php
}
}
?>
}
});
HTML
<div style="display:none">
<div id="data">
<div id="graphic">
</div>
</div>
</div>
Sample code of the link
<a href="#data" class="jogos" id="cat<?php echo $i; ?>jogo<?php echo $j; ?>" >
You have display:none on the parent of your fancybox therefor the grafic isnt displayed.
The Grafic element isn't inside the dom yet if you use display:none initially. Try to use clip: rect instead as a class and add/remove that class using the fancybox callbacks.
Try this code:
$('.jogos').fancybox({
'onStart': function() {
$("#data").removeClass('hidden');
},
'onClosed': function() {
$("#data").addClass('hidden');
}
});
CSS:
.hidden {
clip: rect(1px 1px 1px 1px);
position: absolute;
)}
HTML:
<div>
<div id="data" class="hidden">
<div id="graphic">
</div>
</div>
</div>
I am trying to hide or show the div based on the div id from the php function. I am not able to make it work, please help me.
Javascript:
<script>
showOrHide(id) {
var elem=getElementById(id);
if(elem.style.visibility="hidden")
elem.style.visibility="visible";
else
elem.style.visibility="hidden";
}
</script>
PHP Script:
<?php
function display_link($link_id,$upvote_array,$downvote_array,$divid) {
?>
More links
<div id="<?php echo $divid ?>" style="visibility:hidden;">
</div>
<?php } ?>
Here's a cleaned-up version of your function.
function showOrHide(id) {
var elem = document.getElementById(id);
elem.style.visibility = (elem.style.visibility === 'hidden')? 'visible' : 'hidden';
}
<script>
function showOrHide(id){
var elem = getElementById(id);
if(elem.style.visibility=="hidden"){
elem.style.visibility="visible";
} else {
elem.style.visibility="hidden";
}
}
</script>
<?php
function display_link($link_id,$upvote_array,$downvote_array,$divid)
{
?>
More links
<div id="<?php echo $divid ?>" style="visibility:hidden;">
</div>
1 - visibility == 'hidden'
2 - missing ; after visibility="visible" and ="hidden"
3 - href="javascript:showOrHide('')" - missing '' inside your javascript function
Try this
<script>
function showOrHide(id){
var elem = document.getElementById(id);
elem.style.visibility = (elem.style.visibility === 'hidden')? 'visible' : 'hidden';
}
</script>
<?php
function display_link($link_id,$upvote_array,$downvote_array,$divid)
{
?>
More links
<div id="<?php echo $divid ?>" style="display:hidden;">
</div>
<?php
}
?>
// Here based on the class rply1 I am displaying replies
<div class="biz_gary_btn width80 pl5 fl rply1<?php echo $comm['comment_id'];?>">
<div class="fl pt5_ie pt1"><img src="<?php echo base_url();?>images/green_callot.png" alt="Green Callot"></div>
<div class="arial bold fnt11 c7b7b7b fl pl5 ">2 Replies </div>
</div>
<!--2 Replies-->
<!--Reply-->
<div class="biz_gary_btn width84 pl5 fl rply2<?php echo $comm['comment_id'];?>">
<div class="fl pt5_ie pt1 pl5"><img src="<?php echo base_url();?>images/light_blue_callot.png" alt="Blue Callot"></div>
<div class="arial bold fnt11 c7b7b7b fl pl7">Reply</div>
</div>
This is the script
<script type="text/javascript">
$(document).ready(function(){
$(".rply1<?php echo $comm['comment_id'];?>").click(function(){
alert("sdfsd");
//return true;
$("#2replies<?php echo $comm['comment_id'];?>").toggle();
$(".rply1<?php echo $comm['comment_id'];?>").toggleClass("advice_white_btn_active");
});
$(".rply2<?php echo $comm['comment_id'];?>").click(function(){
$("#reply<?php echo $comm['comment_id'];?>").toggle();
$(".rply2<?php echo $comm['comment_id'];?>").toggleClass("advice_white_btn_active");
});
});
</script>
But the function is being called twice. I can see the alert twice. After the first alert my #2replies div is visible. This working just fine in the HTML set-up.
This might not be ideal because without seeing your full code it is hard to tell if you are actually binding the event twice. But, instead you could ensure that a click event is unbound before binding it again:
<script type="text/javascript">
$(document).ready(function(){
$(".rply1<?php echo $comm['comment_id'];?>").unbind("click").bind("click", function(){
alert("sdfsd");
//return true;
$("#2replies<?php echo $comm['comment_id'];?>").toggle();
$(".rply1<?php echo $comm['comment_id'];?>").toggleClass("advice_white_btn_active");
});
$(".rply2<?php echo $comm['comment_id'];?>").unbind("click").bind("click", function(){
$("#reply<?php echo $comm['comment_id'];?>").toggle();
$(".rply2<?php echo $comm['comment_id'];?>").toggleClass("advice_white_btn_active");
});
});
</script>