May 31, 2010

How to hide jQuery Sub-Menus(ddsmoothmenu)?

Question by Tim Schmelter

I’m new to jQuery and i must admit that i’ve understood nothing yet, the syntax appears to me as an unknown language although i thought that i had my experiences with javascript.
Nevertheless i managed it to implement this menu in my asp.net masterpage’s header.
Even got it to work that the content-page is loaded with ajax with help from here.
But finally i’m failing with the menu to disappear when the new page was loaded asynchronously. I dont know how to hide this accursed jQuery Menu.

Following the part of the js-file where the events are registered for hiding/disappearing. I dont know how to get the part that is responsible for it and even i dont know how to implement that part in my Anchor-onclick function where i dont have a reference to the jQuery Object.

buildmenu:function($, setting){
 var smoothmenu=ddsmoothmenu
 var $mainmenu=$("#"+setting.mainmenuid+">ul") //reference main menu UL
 $mainmenu.parent().get(0).className=setting.classname || "ddsmoothmenu"
 var $headers=$mainmenu.find("ul").parent()
 $headers.hover(
  function(e){
   $(this).children('a:eq(0)').addClass('selected')
  },
  function(e){
   $(this).children('a:eq(0)').removeClass('selected')
  }
 )
 $headers.each(function(i){ //loop through each LI header
  var $curobj=$(this).css({zIndex: 100-i}) //reference current LI header
  var $subul=$(this).find('ul:eq(0)').css({display:'block'})
  $subul.data('timers', {})
  this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
  this.istopheader=$curobj.parents("ul").length==1? true : false //is top level header?
  $subul.css({top:this.istopheader && setting.orientation!='v'? this._dimensions.h+"px" : 0})
  $curobj.children("a:eq(0)").css(this.istopheader? {paddingRight: smoothmenu.arrowimages.down[2]} : {}).append( //add arrow images
   '<img src="'+ (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[1] : smoothmenu.arrowimages.right[1])
   +'" class="' + (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[0] : smoothmenu.arrowimages.right[0])
   + '" style="border:0;" />'
  )
  if (smoothmenu.shadow.enable){
   this._shadowoffset={x:(this.istopheader?$subul.offset().left+smoothmenu.shadow.offsetx : this._dimensions.w), y:(this.istopheader? $subul.offset().top+smoothmenu.shadow.offsety : $curobj.position().top)} //store this shadow's offsets
   if (this.istopheader)
    $parentshadow=$(document.body)
   else{
    var $parentLi=$curobj.parents("li:eq(0)")
    $parentshadow=$parentLi.get(0).$shadow
   }
   this.$shadow=$('<div class="ddshadow'+(this.istopheader? ' toplevelshadow' : '')+'"></div>').prependTo($parentshadow).css({left:this._shadowoffset.x+'px', top:this._shadowoffset.y+'px'})  //insert shadow DIV and set it to parent node for the next shadow div
  }
  $curobj.hover(
   function(e){
    var $targetul=$subul //reference UL to reveal
    var header=$curobj.get(0) //reference header LI as DOM object
    clearTimeout($targetul.data('timers').hidetimer)
    $targetul.data('timers').showtimer=setTimeout(function(){
     header._offsets={left:$curobj.offset().left, top:$curobj.offset().top}
     var menuleft=header.istopheader && setting.orientation!='v'? 0 : header._dimensions.w
     menuleft=(header._offsets.left+menuleft+header._dimensions.subulw>$(window).width())? (header.istopheader && setting.orientation!='v'? -header._dimensions.subulw+header._dimensions.w : -header._dimensions.w) : menuleft //calculate this sub menu's offsets from its parent
     if ($targetul.queue().length<=1){ //if 1 or less queued animations
      $targetul.css({left:menuleft+"px", width:header._dimensions.subulw+'px'}).animate({height:'show',opacity:'show'}, ddsmoothmenu.transition.overtime)
      if (smoothmenu.shadow.enable){
       var shadowleft=header.istopheader? $targetul.offset().left+ddsmoothmenu.shadow.offsetx : menuleft
       var shadowtop=header.istopheader?$targetul.offset().top+smoothmenu.shadow.offsety : header._shadowoffset.y
       if (!header.istopheader && ddsmoothmenu.detectwebkit){ //in WebKit browsers, restore shadow's opacity to full
        header.$shadow.css({opacity:1})
       }
       header.$shadow.css({overflow:'', width:header._dimensions.subulw+'px', left:shadowleft+'px', top:shadowtop+'px'}).animate({height:header._dimensions.subulh+'px'}, ddsmoothmenu.transition.overtime)
      }
     }
    }, ddsmoothmenu.showhidedelay.showdelay)
   },
   function(e){
    var $targetul=$subul
    var header=$curobj.get(0)
    clearTimeout($targetul.data('timers').showtimer)
    $targetul.data('timers').hidetimer=setTimeout(function(){
     $targetul.animate({height:'hide', opacity:'hide'}, ddsmoothmenu.transition.outtime)
     if (smoothmenu.shadow.enable){
      if (ddsmoothmenu.detectwebkit){ //in WebKit browsers, set first child shadow's opacity to 0, as "overflow:hidden" doesn't work in them
       header.$shadow.children('div:eq(0)').css({opacity:0})
      }
      header.$shadow.css({overflow:'hidden'}).animate({height:0}, ddsmoothmenu.transition.outtime)
     }
    }, ddsmoothmenu.showhidedelay.hidedelay)
   }
  ) //end hover
 }) //end $headers.each()
 $mainmenu.find("ul").css({display:'none', visibility:'visible'})
}

one link of my menu what i want to hide when the content is redirected to another page(i need “closeMenu-function”):

<li><a href="DeliveryControl.aspx" onclick="AjaxContent.getContent(this.href);closeMenu();return false;">Delivery Control</a></li>

In short: I want to fade out the submenus the same way they do automatically onblur, so that only the headermenu stays visible but i dont know how.

Thanks, Tim

EDIT: thanks to Starx’ private-lesson in jQuery for beginners i solved it:
I forgot the # in $(“#smoothmenu1”). After that it was not difficult to find and call the hover-function from the menu’s headers to let them fade out smoothly:

$("#smoothmenu1").find("ul").hover(); 

Regards,
Tim

Answer by Starx

Ok, I didn’t read your whole post. But if you are using a jQuery Menu, that menu should having a container element like <div> or <ul> and they will either have a class or id

In case it is a id then do

$(document).ready(function() {
      $("#myelementid").hide();
});

In case it has a class then do

$(document).ready(function() {
      $(".myelementclass").hide();
});

Hope this helps

UPDATE

$("#mainmenu").children().hide(); // to hide all child elements

or

$(".submenu").hide(); //to hide every submenu

Dynamically loading external HTML in a div using Java Script

Question by user354051

I have prepared some demo examples for the topic.
There is page name “changelog.html” here:

http://pantheon-studios.in/test/jquery/changelog.html

This is working fine if loaded directly.

I am trying to load this page dynamically into:

http://pantheon-studios.in/test/jquery/index.html

Here changelog.html doesn’t behaving as expected.

I think the init script on changelog.html is not getting executed or something else is happening when loading it dynamically.

Like wise I do have couple of other pages using various jQuery and other java scripts plugins. Some of those needs initialization like animatedcollapse.js in the above example, and couple of them doesn’t need initialization, you can directly call the script and go.

I also gave a try using:

jQuery.getScript("anim.js")

after dynamically loading “changelog.html” but doesn’t work.

The “anim.js” contains

animatedcollapse.addDiv('cat', 'fade=0,speed=400,group=pets,hide=1');
animatedcollapse.addDiv('dog', 'fade=0,speed=400,group=pets,hide=1');
animatedcollapse.addDiv('rabbit', 'fade=0,speed=400,group=pets,hide=1');
animatedcollapse.init();

I would really appreciate is some one point me out the right direction. I am completely new to web programming so please have some patience with me.

Thanks

Answer by Starx

I solved your problem

your index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">

<head>    
    <!-- Java Scripts -->
    <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#clickme").click(function() { 
                $("#content").load("changelog.html");
            });
        });
    </script>
</head>

<body>
    <a href="javascript:void(0)" id="clickme">Load HTML</a>            
    <div>
        <div id="content"></div>
    </div>

</body>
</html>

Your changelog.html

    <script type="text/javascript" src="js/animatedcollapse.js"></script>
    <script type="text/javascript">

        animatedcollapse.addDiv('cat', 'fade=0,speed=400,group=pets,hide=1');
        animatedcollapse.addDiv('dog', 'fade=0,speed=400,group=pets,hide=1');
        animatedcollapse.addDiv('rabbit', 'fade=0,speed=400,group=pets,hide=1');



    animatedcollapse.ontoggle=function($, divobj, state){ //fires each time a DIV is expanded/contracted
        //$: Access to jQuery
        //divobj: DOM reference to DIV being expanded/ collapsed. Use "divobj.id" to get its ID
        //state: "block" or "none", depending on state
    };        
    animatedcollapse.init();    

    </script>    
    <!-- CSS Stylesheet -->
    <style type="text/css">
    .topicdetail{
    text-align:justify;
    width:650px;
    padding-left:10px;
    padding-right:10px;
    /*background: #BDF381;*/
    font-size: 13px;
    }
    </style>
    <div id="container">      
        <ul>
      <li>Compilation command in preferences is more simplified.<a href="javascript:animatedcollapse.toggle('cat')">?</a>
            <div id="cat" class='topicdetail'>

                <br/>
                <p>
                The cat (Felis catus), also known as the domestic cat or house cat to distinguish it from other felines,
                is a small carnivorous species of crepuscular mammal that is often valued by humans for its companionship
                and its ability to hunt vermin. It has been associated with humans for at least 9,500 years.
                A skilled predator, the cat is known to hunt over 1,000 species for food. It can be trained to obey simple 

commands. 
                </p>
                <br/>
            </div>
          </li>

          <li>Compilation command in preferences is more simplified.<a href="javascript:animatedcollapse.toggle('dog')">?</a>

          <div id="dog" class='topicdetail'>
                <br/>
                <p>
                The cat (Felis catus), also known as the domestic cat or house cat to distinguish it from other felines,
                is a small carnivorous species of crepuscular mammal that is often valued by humans for its companionship
                and its ability to hunt vermin. It has been associated with humans for at least 9,500 years.
                A skilled predator, the cat is known to hunt over 1,000 species for food. It can be trained to obey simple 

commands. 
                </p>
                <br/>
            </div>
          </li>

          <li>Compilation command in preferences is more simplified.<a href="javascript:animatedcollapse.toggle('rabbit')">?

</a>

          <div id="rabbit" class='topicdetail'>
                <br/>
                <p>
                The cat (Felis catus), also known as the domestic cat or house cat to distinguish it from other felines,
                is a small carnivorous species of crepuscular mammal that is often valued by humans for its companionship
                and its ability to hunt vermin. It has been associated with humans for at least 9,500 years.
                A skilled predator, the cat is known to hunt over 1,000 species for food. It can be trained to obey simple 

commands. 
                </p>
                <br/>
            </div>
          </li>
        </ul>    
    </div>

Just copy and paste the html

finding a way to track website users

Question by sdr

I want to know that is there any way to know after which page an user is leaving the website.

So that I can track that page and work to improve the content of that page.

I am using PHP as backend code.

Answer by Starx

If you want to see which is the last page a user is visiting, you can do something like this

I am assuming that you have a mysql connection already provided.
Create a page like “session.php” and place this function

function trackpage($pagename) {
    if(!isset($_SESSION)) { 
       // if the user is visiting the website for the first time
       session_start();
       $query = "INSERT INTO `newusers` VALUES(NULL, '$pagename');";
       //In case table 'newuser' have two fields 'id' and 'page' to keep a track of page
       $result = mysql_query($query) or die(mysql_error());
       $_SESSION['userid'] = mysql_insert_id();
    }
    else {
       //if he is just visiting another page
       $query = "UPDATE `newusers` SET page='$pagename' WHERE id='".$_SESSION['userid']."';";
       $result = mysql_query($query) or die(mysql_error());   
    }
}

Npw you need to include this on every page. on the top write this

<?
include "session.php";
trackpage("index.php");
?>

Now you know on what page are people leaving the website

May 28, 2010

How do i hide html until its processed with javascript?

Question by acidzombie24

I am using some JS code to transform my menu into a drilldown menu.

The problem is before it runs the JS you see a BIG UGLY mess of links. On their site its solved by putting the js at the top. Using recommendations by yahoo/YSlow i am keeping the JS files at the bottom.

I tried hiding the menu with display:none then using jquery to .show(), .css(‘display’, ”), .css(‘display’, ‘block’) and they all lead up to a messsed up looking menu (i get the title but not the title background color or any links of the menu)

How do i properly hide a div/menu and show it after being rendered?

Answer by acidzombie24

I found the solution. I should let the links be hidden with css then .show() BEFORE the ddMenu code executes instead of after. The ddMenu seems to check the parents width and sinces its hidden i guess its 0. The time between .show() and ddMenu is fast enough not to show the ugly links (on my machine/browser). The the majority of the time (page loading, http req for the JS files, JS compiling/exec etc) the links are hidden so it looks pretty good.

$(function () {
    $('.menuT1').show(); //do it before not after in this case.
    $('.menuT1 > ul').ddMenu({

Answer by Starx

Well, If you are familiar with jquery then I would do something like this

$("#mybuttom").click(function() {
           $("#mydiv").hide(); //hide the div at the start of process
           $.post( "mypostpage.php", 
                   { testvar: testdata },
                   function(data) {
                         //callback function after successful post
                         $('#mydiv').show(); //show it again
                   }
           );
});

CSS nested div height 100%

Question by Aaron Moodie

I’ve currently got the #border div at 100% of the page height, but am trying to get the #container div to stretch to 100% inside #border. At the moment #container only stretches to fit the content inside it.

* {
    margin: 0;
}

html, body {
    height:100%;
    font-family: Georgia, Times, "Times New Roman", serif;
    font-size:13px;
    line-height:19px;
    color:#333333;
    background: #f5f1ec;
    text-align: left;
}

#border {
    background: #f5f1ec;
    border:solid 1px #FFFFFF; 
    width: 880px;
    margin: 40px auto 0;
    padding:10px;
    height: auto !important;
    min-height: 100%;
    height: 100%;
}

#container {
    background: #FFFFFF;
    padding: 10px 50px 0;
    height: 100%;
}

Answer by Starx

Solved:

#container {
    background: #FFFFFF;
    padding: 10px 50px 0;
    height: 100%;
    width:780px;
    position:absolute;
}
May 27, 2010

How to show hidden div when javascript is disabled?

Question by Jitendra Vyas

I’m hiding a div using display:none and this div only shows when we click on + icon. but if JavaScript is disabled then I want to show that div by default on. How to do this?

I can’t post whole code for now.

jQuery(document).ready(function() {
  jQuery('a#toggle').click(function() {
       jQuery('#map').slideToggle(400);
       return false;

});

CSS

#map {display:none}

Answer by deceze

Only hide it if Javascript is enabled:

<head>
    <script type="text/javascript" charset="utf-8">
        document.write('<style type="text/css" media="screen">#map { display: none; }</style>');
    </script>
</head>

Answer by Starx

I think

<noscript>Your browser does not support JavaScript!</noscript>

This would be a better idea that other

Put the division you want to show if the javascript is not enable inside <noscript> tags

May 26, 2010

Best way to install multiple versions of Apache, PHP and MySQL on a single FreeBSD host

Question by Mikael Roos

I want a test- and development-environment for web using Apache, PHP and MySQL. I need to be able to test a single web-application with multiple versions of PHP (5.2, 5.3, etc) and multiple versions of MySQL (5.0, 5.1, 5.5, etc). It shall be hosted on a FreeBSD server.

My idea is to compile each version into a directory structure and running them on separate portnumbers. For example:

opt/apache2.2-php5.2-mysql-5.0 
(httpd on port 8801, mysql on port 8802)
(directory contains each software, compiled and linked towards eachother)

opt/apache2.2-php5.3-mysql-5.1 
(httpd on port 8803, mysql on port 8804)
(and so on)

Any thoughts or suggestions of the best way to setup this type of environment?

UPDATE:
Question moved to serverfault:
http://serverfault.com/questions/145504/best-way-to-install-multiple-versions-of-apache-php-and-mysql-on-a-single-freebs

Answer by Starx

Simple PHP upload form not working

Question by Lea

I seem to run into so many issues when dealing with writing to directories. If someone could please look over this script, and tell me why it’s not working, I’d be so appreciative.

Upon uploading the file from the form, I don’t get anything.. It doesnt output any errors, it simply just refreshes.

Thanks, Lea

<?php include ('config.php');
 if( isset($_POST['submit']) ) {

$target = ''.$_SERVER['DOCUMENT_ROOT'].'/images/';
$target = $target . basename( $_FILES['photo']['name']) ;
$url = basename( $_FILES['photo']['name']) ;

if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
$moved =  "File has been moved to location $target";

$name = mysql_real_escape_string($_POST['photoname']);
mysql_query("INSERT INTO photos (photo_name, photo_image) VALUES ('$name',  '$url' )") or die(mysql_error());
$success = "Photo has been added!";

  } else {

$moved = "File has not been moved to $target";
$success = "Failed to upload:(";

  }

} ?>

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Photo Upload</title>
<meta name="robots" content="index, follow" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<link href="<?php echo $globalurl; ?>styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="holder">
<br /><br />
<b>Add a new photo</b>
<hr />
<br />
<b><?php echo "$success<br />"; ?>
<?php echo "$moved<br />"; ?></b>
  <form enctype="multipart/form-data" method="post" action="<?php echo $PHP_SELF; ?>">
    <table cellspacing="0" cellpadding="0" width="500px">
      <tbody>
        <tr>
          <td valign="top">Photo Name:</td>
          <td valign="top">
            <input type="text" name="photoname" /><br />
            <br />
            </td>
        </tr>
        <tr>
          <td valign="top">Photo:</td>
          <td valign="top">
  <input type="file" name="photo"><br />
            <br />
            </td>
        </tr>
      </tbody>
    </table>
    <input type="submit" value="submit" />
  </form>
</div>
</body>
</html>

Answer by Victor Stanciu

Without checking the PHP code for errors, the first thing that stands out is that this:

isset($_POST['submit'])

always returns false. The input type=”submit” must have the name attribute “submit” in order to be sent:

<input type="submit" value="submit" name="submit" />

Answer by Starx

Ok done

<?php 
if( isset($_POST['submit']) ) {
 $target = 'images/';
 echo $target = $target . basename( $_FILES['photo']['name']) ;

 if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
  $moved =  "File has been moved to location $target"; 
  $success = "Photo has been added!";
 } 
 else { 
 $moved = "File has not been moved to $target";
 $success = "Failed to upload:(";
  }
} 
?>

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Photo Upload</title>
<meta name="robots" content="index, follow" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<link href="<?php echo $globalurl; ?>styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="holder">
<b>Add a new photo</b>
<?php echo "$success<br />"; ?>
<?php echo "$moved<br />"; ?>
  <form enctype="multipart/form-data" method="post" action="<? echo $_SERVER['PHP_SELF']; ?>">
    <table cellspacing="0" cellpadding="0" width="500px">
      <tbody>
        <tr>
          <td valign="top">Photo Name:</td>
          <td valign="top">
            <input type="text" name="photoname" /><br />
            <br />
            </td>
        </tr>
        <tr>
          <td valign="top">Photo:</td>
          <td valign="top">
    <input type="file" name="photo">
            </td>
        </tr>
      </tbody>
    </table>
    <input type="submit" value="submit" id="submit" name="submit" />
  </form>
</div>
</body>
</html>
May 25, 2010

CSS – Advantages of single image file vs multiple files

Question by Hamish

I have noticed that alot of sites now, have all of their images in single files are then use background-position to offset the rectangle which is shown on the screen.

Is this for performance reasons? If so why?

Answer by Oli

Is this for performance reasons? If so why?

  1. A single request means fewer concurrent connections to the server meaning other things can be loading. A TCP connection also costs resources on the server. Fewer total connections per user means more users can use it at once (if your performance is really connection bound).

  2. A single sprite usually has a slightly smaller filesize than a bunch of single images, though this is not guaranteed and different formats vary.

  3. Object states are all loaded at once meaning interaction is much more immediate than if you loaded another state on demand.

  4. Even if part of the sprite isn’t used on the current page, by loading it (and the browser caching it), this would speed up the browsing experience for the user later on when the user views other pages.

Sprites don’t fix everything and you probably shouldn’t get too anal about it until you’re forecasting heavy traffic and/or you’re moving to a CDN where you’re charged per request.

Of course if you have a whole load of 16×16 icons that get used in a single place, you could sprite them up very quickly. I find having several sprites for specific things like that actually makes the CSS a lot cleaner too.

Answer by Starx

And one more thing that @david didn’t mention is, its going to take a lot of server time to load several small images, instead load one big image in one go(request) and manipulate it as your choicee

How to know the file type of the file which you are forcing the user to download?

Question by Starx

I am trying to force the user to download a file. For that my script is:

$file = "filethis.zip";        
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip"); //This is what I need
header("Content-Transfer-Encoding: binary");
readfile($file);

The files I am going to upload my not be .zip all the time so I want to know the content type of the image I am going to receive in $file.
How to accomplish this

Answer by cjk

I always put application/octet-stream (or somwething like that) as the browser can’t then try and display it in any way, it will always force the user to Save / Run, then the file type is often inferred by the extension.

Answer by Starx

Ok, I did it myself.

I used

$type = filetype($file); //to know the type
...

Please fill the form - I will response as fast as I can!