If css() == X, else, not working, forms not working - javascript

I'm doing a chat for my social network. I'm using the following code and it seems to work while showing chat, but not while hiding it. You can see it on http://live-pin.com at the right bottom corner (the "system" bar).
What am I doing bad?
function toggleChat(obj){
current_margin = $(obj).css('marginBottom');
if (current_margin == 0){
$(obj).animate({marginBottom : "-270px"}).removeClass("active_box").addClass("hidden_box");
}else{
$(obj).animate({marginBottom : "0"}).removeClass("hidden_box").addClass("active_box");
}
}
Also, I'm having troubles because it shows/hides both chats & I don't want that to happen, and the "NEW MESSAGE" form doesn't work, just in the last chat created. As an additional detail, the boxes are created dynamically with data retrieved from JSON, so I can't use click() function or similars.
<?php echo "Thanks! (:"; ?>

Even though you can set the marginBottom to 0 it will internally be 0px, thus current_margin will be 0px which is not 0.
But you may try to parse the value first:
function toggleChat(obj) {
var currentMargin = parseInt($(obj).css('margin-bottom'));
if (currentMargin === 0) {
$(obj).animate({ marginBottom: "-270px" })
.removeClass("active_box")
.addClass("hidden_box");
} else {
$(obj).animate({marginBottom : "0px"})
.removeClass("hidden_box")
.addClass("active_box");
}
}

Related

Using qTip2 with Handsontable

I want to use qTip and Handsontable at the same time.
So I made a grid with Handsontable and when the user submits it, ajax sends the cells that are not correct. Then, with a callback function, I want to color the cells in the wrong format and display a bubble with qTip2.
My problem is when I want to create a bubble on a specific cell, it doesn't work.
Here is my code :
function insertTraitementCallback(responseObject,ioArgs)
{
var jsonobject = eval(responseObject);
$("td").eq(jsonobject[item]+11).qtip({ //It doesn't work
content : '<div id="bulle">test</div>'
});
for(var item in jsonobject)
{
if((item % 2 ) == 0)
{
$("td").eq(jsonobject[item]+11).css("background-color","red"); //It works
}else
{
}
}
}
Please help !

Unable to update div based on current value inside it

I have a php page that shows the server logs in a web interface. It is pretty simple. Basically there is an ajax call inside a setinterval() which hits a backend php file, which will read the log and echo it. The relevant code is:
setInterval(function()
{
$.get("log.php",{logId: $('#logId').val()}, function(data)
{
$("#logDetails").html(data);
//scroll to the bottom when updated...
$("#logDetails").stop().animate({scrollTop: $("#logDetails")[0].scrollHeight}, 800);
});
}, 2000);
As you can see, this just update a div with an id called logDetails with content from the log file in the server.
The div has a style="overflow:scroll" and the line $("#logDetails").stop().animate.. is to scroll to the bottom of the div when new content is added. All this works very well.
If a user has scrolled up the div and is examining the logs, and new content comes in then the div scrolls down. That is also fine. The problem is that the server log can have many hours of inactivity. During that time, when the user scrolls up, since setinterval is still working, he gets scrolled down even though new content is not available. This can become a real nuisance.
I wanted to handle this in the minimal way possible and I thought doing this might suffice:
$.get("log.php",{logId: $('#logId').val()}, function(data)
{
//new condition to check id new content has come
if($('#logDetails').val() != data)
{
//update div and scroll to the bottom..
}
...
However this is not working. I am aware of other ways like check the log modified time in server side etc, but I cannot modify any of those files due to other reasons.
So my question is - why does this not work? And how can I do this inside the interface file itself instead of resorting to other means?
The PHP code that pushes out the log is:
$contents = "";
$handle = #fopen($logFile, 'r');
if($handle)
{
while(($line = fgets($handle)) !== false)
{
//highlight errors
$txt = "Execution stopped because of error";
if(strstr($line,$txt))
{
$line = "<span style='color:red'>".$line."</span>";
}
$contents .= $line;
}
}
#fclose($handle);
echo nl2br($contents);
It would be difficult to exactly pinpoint what is wrong since you mentioned the data coming from the log will by dynamic. However you can figure it out by:
Do a console.log of $('#logDetails').val() and data
Then use a diff software like kDiff to find out what their differences are.
Once you find the differences, then you can think about ways to solve it.
Hope that helps!
.val() is unlikely to work, but since you haven't provided the contents of the html you're trying to work with, we can only offer suggestions. try either $('#logDetails').text() as mentioned in djidi's comment or $('#logDetails').html().
You could try this to make sure you are only ever getting new data back. Obviously I don't know anything about your system so this would have to be modified to work with the data you have:
$contents = "";
$handle = #fopen($logFile, 'r');
$lastHash = !empty($_GET['last_hash']) ? $_GET['last_hash'] : nulll
if($handle)
{
$stale = true;
while(($line = fgets($handle)) !== false)
{
//highlight errors
$txt = "Execution stopped because of error";
if(strstr($line,$txt))
{
$line = "<span style='color:red'>".$line."</span>";
}
if (empty($lastHash) || md5($line) == $lastHash) {
// this is the last stale line
$stale = false;
}
if (!$stale) {
$contents .= $line;
$lastHash = md5($line);
}
}
}
#fclose($handle);
echo json_encode(array('log_data' => nl2br($contents), 'last_hash'=> $lastHash));
and in javascript:
var lastHash = null;
setInterval(function()
{
$.getJSON("log.php",{logId: $('#logId').val(), last_hash : lastHash}, function(data)
{
lastHash = data.last_hash
if (data.log_data && data.log_data.length) {
$("#logDetails").html(data.log_data);
//scroll to the bottom when updated...
$("#logDetails").stop().animate({scrollTop: $("#logDetails")[0].scrollHeight}, 800);});
}
}, 2000);

jQuery conditionally change events depending on .html( 'string' ) values

http://jsfiddle.net/motocomdigital/Qh8fL/4/
Please feel free to change the heading if you think I've worded it wrong.
General
I'm running a wordpress site with multilingual control. And my menu/navigation is dynamic, controlled via the wordpress admin. The multilingual language plugin also changes the dynamic menu/navigation content, as well as page content.
My Contact button, which is in the dynamic navigation, opens a sliding menu using jQuery. Very simple animation using top css. The contact button is on the page twice, hence why I'm not using the .toggle for iterations. See jsFiddle.
Script
var $button = $(".contact-button"),
// var for button which controls sliding div
$slide = $("#content-slide");
// var for the div which slides up and down
$button.on('click', function () {
// function for when button is clicked
if ($button.html() == 'Close') {
// run this if button says 'Close'
$slide.stop().animate({ top: "-269px" }, 300);
// close slide animation
$button.html('Contact');
// change text back to 'Contact'
} else {
// else if button says Contact or anything else
$slide.stop().animate({ top: "0" }, 300);
// open slide animation
$button.html('Close');
// change text to 'Close'
}
});
Problem
Because I'm running multilingual on the site. The navigation spelling changes. See jsFiddle flag buttons for example. This is fine, the animation still runs OK, because it's using the button class 'contact-button'.
But because I'm using the .html to replace the text of the button to "Close" and then on the second iteration, back to "Contact" - obviously this is a problem for other languages, as it always changes to English 'close' and back to English 'Contact'
But my three languages and words that I need the iterations to run through are...
Contact - Close
Contatto - Cerca
Contacto - Chiudere
Can anyone help me expand my script to accommodate three languages, all my attempts have failed. The jsFiddle has the script.
The language functionality in the fiddle is only for demo purposes, so the iteration sequence can be tested from the beginning. I understand if you change the language whilst the menu is open (in the fiddle), it will confused it. But when the language is changed on my site, the whole page refreshes, which closes the slide and resets the sequence. So it does not matter.
Any pro help would be awesome thanks!!!
MY POOR ATTEMPT, BUT YOU CAN SEE WHAT I'M TRYING TO ACHIEVE
var $button = $(".contact-button"),
// Var for button which controls sliding div
$slide = $("#content-slide");
// Var for the div which slides up and down
$button.on('click', function () {
// function for when button is clicked
if ($button.html() == 'Close' || 'Cerca'|| 'Chiudere' ) {
// run this if button says Close or Cerca or Chiudere
$slide.stop().animate({ top: "-269px" }, 300);
// Close slide animation
$(function () {
if ($button.html(== 'Close') {
$button.html('Contact'); }
else if ($button.html(== 'Cerca') {
$button.html('Contatto'); }
else ($button.html(== 'Chiudere') {
$button.html('Contacto'); }
});
// Change text back to Contact in correct language
} else {
// else if button says Contact or anything else
$slide.stop().animate({ top: "0" }, 300);
// Open slide animation
$(function () {
if ($button.html(== 'Contact') {
$button.html('Close'); }
else if ($button.html(== 'Contatto') {
$button.html('Cerca'); }
else ($button.html(== 'Contacto') {
$button.html('Chiudere'); }
});
// Change text back to Close in the correct language
}
});
See my attempt script above which is not working on this jsFiddle.
Here's a working example: http://jsfiddle.net/Qh8fL/2/
When one of the language buttons gets clicked, it stores the strings for Contact and Close using jQuery's .data() method. Then, when the contact/close button gets clicked, it refers to those strings rather than having it hard-coded.
Here are the relevant lines of code:
$("#english").click(function() {
$(".contact-button").html('Contact').data('langTxt',{contact:'Contact',close:'Close'});
});
$("#spanish").click(function() {
$(".contact-button").html('Contatto').data('langTxt',{contact:'Contatto',close:'Close'});
});
$("#italian").click(function() {
$(".contact-button").html('Contacto').data('langTxt',{contact:'Contacto',close:'Close'});
});
if ($button.html() == 'Close') {
//...
$button.html($button.data('langTxt').contact);
} else {
//...
$button.html($button.data('langTxt').close);
}
All you need to do to modify the "close" text appropriately is by editing the close property inside the calls to data() that occur in each of the click events.
You should never depend on label strings ... especially in a multilingual environment. Instead you should use placeholders that you store in an attribute (maybe using .data()). Then you write your own setters for the labels depending on the value of the attribute.
var myLabels = {'close': ['Close', 'Cerca', 'Chiudere'], 'contact' : ['Contact', 'Contatto', 'Contacto']};
var currLang = 2; // to select italian
....
// to set the label
$button.data('mylabel', 'close');
$button.html(myLabels['close'][currLang]);
....
if($button.data('mylabel') == 'close') {
$button.data('mylabel', 'contact');
$button.html(myLabels['contact'][currLang]);
} else {
$button.data('mylabel', 'close');
$button.html(myLabels['close'][currLang]);
}

ExtJS Change Event Listener failing to fire

I was asked to post this as a question on StackOverflow by http://twitter.com/jonathanjulian which was then retweeted by several other people. I already have an ugly solution, but am posting the original problem as requested.
So here's the back story. We have a massive database application that uses ExtJS exclusively for the client side view. We are using a GridPanel (Ext.grid.GridPanel) for the row view loaded from a remote store.
In each of our interfaces, we also have a FormPanel (Ext.form.FormPanel) displaying a form that allows a user to create or edit records from the GridPanel. The GridPanel columns are bound to the FormPanel form elements so that when a record is selected in the GridPanel, all of the values are populated in the form.
On each form, we have an input field for the table row ID (Primary Key) that is defined as such:
var editFormFields = [
{
fieldLabel: 'ID',
id: 'id_field',
name: 'id',
width: 100,
readOnly: true, // the user cannot change the ID, ever.
monitorValid: true
} /* other fields removed */
];
So, that is all fine and good. This works on all of our applications. When building a new interface, a requirement was made that we needed to use a third-party file storage API that provides an interface in the form of a small webpage that is loaded in an IFrame.
I placed the IFrame code inside of the html parameter of the FormPanel:
var editForm = new Ext.form.FormPanel({
html: '<div style="width:400px;"><iframe id="upload_iframe" src="no_upload.html" width="98%" height="300"></iframe></div>',
/* bunch of other parameters stripped for brevity */
});
So, whenever a user selects a record, I need to change the src attribute of the IFrame to the API URL of the service we are using. Something along the lines of http://uploadsite.com/upload?appname=whatever&id={$id_of_record_selected}
I initially went in to the id field (pasted above) and added a change listener.
var editFormFields = [
{
fieldLabel: 'ID',
id: 'id_field',
name: 'id',
width: 100,
readOnly: true, // the user cannot change the ID, ever.
monitorValid: true,
listeners: {
change: function(f,new_val) {
alert(new_val);
}
}
} /* other fields removed */
];
Nice and simple, except that it only worked when the user was focused on that form element. The rest of the time it failed to fire at all.
Frustrated that I was past a deadline and just needed it to work, I quickly implemented a decaying poller that checks the value. It's a horrible, ugly hack. But it works as expected.
I will paste my ugly dirty hack in an answer to this question.
"The GridPanel columns are bound to
the FormPanel form elements so that
when a record is selected in the
GridPanel, all of the values are
populated in the form."
As I understand it from the quote above, the rowclick event is what actually triggers the change to your form in the first place. To avoid polling, this could be the place to listen, and eventually raise to your custom change event.
Here is the ugly hack that I did to accomplish this problem:
var current_id_value = '';
var check_changes = function(offset) {
offset = offset || 100;
var id_value = document.getElementById('id_field').value || '';
if ( id_value && ( id_value != current_id_value ) ) {
current_id_value = id_value;
change_iframe(id_value);
} else {
offset = offset + 50;
if ( offset > 2500 ) {
offset = 2500;
}
setTimeout(function() { check_changes(offset); }, offset);
}
};
var change_iframe = function(id_value) {
if ( id_value ) {
document.getElementById('upload_iframe').src = 'http://api/upload.php?id=' + id_value;
} else {
document.getElementById('upload_iframe').src = 'no_upload.html';
}
setTimeout(function() { check_changes(100); }, 1500);
};
It's not pretty, but it works. All of the bosses are happy.
If you took a moment to read the source, you would see that the Ext.form.Field class only fires that change event in the onBlur function

JQuery/Javascript works on & off

I am using JQuery 1.3.2-min in a project to handle JavaScript animations, ajax, etc. I have stored the file on the same server as the site instead of using Google. When I run the site locally on my development machine, everything works fine in FF, IE, Opera, and Safari (all the latest versions - I work from home and I only have 1 machine for personal use and development use) except for some CSS differences between them and when I go to the live site on my machine it works fine also. I have cleared my caches and hard refreshed the page, and it still works.
This is where it gets interesting however. When I send the site to my boss to test in various OS/Browser configurations, one page doesn't work correctly, some of it works, some doesn't. Also, the client (who uses IE 8) has also confirmed that it is not completely working - in fact he has told me that the page will work fine for a hour, and then just "turn off" for a while. I have never heard of this sort of thing before, and google isn't turning too much up. I have a hunch it may partly be with JQuery's .data(), but I'm not sure.
The page is basically nested unordered lists, and three basic actions happen on the list.
The top most unordered list is set to visible (all list via css are set to display: none to keep them hidden on a fresh page request); all list items divs are given a hover action of full opacity on mouseon, and faded back to 50% opacity on mouseoff; and then whenver a paragraph is clicked, the top most unordered list in that list item is displayed.
Here is my Javascript file for the page:
$(function() {
// Set first level ul visible
$('div#pageListing ul:first').css('display', 'block');
// Disable all the hyperlinks in the list
$('div#pageListing li a').click(function() {
var obj;
obj = $(this).parent(0).parent('div:first');
highlight(obj);
return false;
});
// List Item mouse hovering
$('#pageListing li').hover(
// Mouse On
function() {
if ($(this).children('div').attr('id') !== 'activePage') {
$(this).children('div').css('opacity', 1).css('filter',
'alpha(opacity=100)');
}
}, // Mouse off
function() {
if ($(this).children('div').attr('id') !== 'activePage') {
$(this).children('div').css('opacity', 0.4).css('filter',
'alpha(opacity=40)');
}
});
// Active list item highlighting
$('#pageListing li div').click(function() {
highlight($(this));
});
// Sub-list expanding/collapsing
$('#pageListing p.subpageslink').click(function() {
// Get next list
var subTree = $(this).parent('div').next('ul');
// If list is currently active, close it, else open it.
if (subTree.data('active') != true) {
subTree.data('active', true);
subTree.show(400);
} else {
subTree.data('active', false);
subTree.hide(400);
}
});
// Double clicking of list item - edit a page
$('#pageListing li div').dblclick(function() {
var classes = $(this).attr('class');
var classArray = classes.split(' ');
var pageID = classArray[1];
editPage(pageID);
});
// Handle button clicking
$('button#addPage').click(function() {
addPage();
});
$('button#editPage').click(function() {
var div = $('div#activePage');
var classes = div.attr('class');
var classArray = classes.split(' ');
var pageID = classArray[1];
editPage(pageID);
});
$('button#delPage').click(function() {
var div = $('div#activePage')
var classes = div.attr('class');
var classArray = classes.split(' ');
var pageID = classArray[1];
delPage(pageID);
});
});
// Highlighting of page when clicked
function highlight(obj) {
// Get previous hightlighted element
// and un-highlight
var oldElement = $('div#activePage');
oldElement.css('background', 'white');
oldElement.css('opacity', 0.4).css('filter', 'alpha(opacity=40)');
oldElement.removeAttr('id');
// highlight current selection
obj.attr('id', 'activePage');
obj.css('opacity', 1).css('filter', 'alpha(opacity=100)');
obj.css('background', '#9dc0f4');
// add appropiate action buttons
$('button.pageButton').css('display', 'inline');
}
function addPage() {
window.location = "index.php?rt=cms/editPage";
}
function delPage(page) {
var confirm = window.confirm("Are you sure? Any sub-pages WILL BE deleted also.");
if (confirm) {
var url = './components/cms/controller/forms/deletePage.php';
$.ajax( {
url : url,
type : 'GET',
data : 'id=' + page,
success : function(result) {
if (!result) {
document.location = "index.php?rt=cms";
} else {
window.alert('There was a problem deleting the page');
}
}
});
}
}
function editPage(page) {
var url = "index.php?rt=cms/editPage/" + page;
window.location = url;
}
Is it possible that you are linking to (some of) the script files using a src that points to a file on your local disk/HDD? If so, that would explain why it works only on your machine, as then only your machine has access to the script file.
Thank you one and all for your suggestions. The end problem was miscommunication. I work from home, and upload my projects to a SVN server, which the boss then uses to update the live server. Somehow, the correct files were not getting updated - a communication error on my part. Another possible reason was that the page, while being declared XHTML 1.0 Strict, had something like 50 validation errors (mosting incorrectly nested UL), and I cleaned that up to 5 errors. So thank you all, but again a sad example of the importance of team work communication.

Categories

Resources