...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
April 25, 2011

JQuery .val(value)

Question by Suzanne

Could anyone help me understand how this code segment works? I’m assuming it produces something like <option value="val">text</option>, but I just don’t see how it does that.

$('<option></option>').val(val).html(text)

The above snippet is part the following code I used to add two options to a <select> statement.

var myOptions = {val1:'text1', val2:'text2'};
$.each(myOptions, function(val, text)
{
   $('#mySelect').append($('<option></option>').val(val).html(text));
}

Answer by Starx

Basically, it interprets as

<option value="val">text</option>

Detailed:

  • $('<option></option>'): Creates a new option element

  • .val(val): Gives it the value val

  • .html(text): Inserts a Text for the option

    var myOptions = {val1:'text1', val2:'text2'};: It defines an array which contains the value and text which is used to populate the select box

$.each(myOptions, function(val, text) {}: This part interate over all the myOptions available and receives the value as val and text as text.

The $('#mySelect').append part adds the above markup (<option value="val">text</option>) into the select box $('#mySelect') at the end.

Read more
April 24, 2011

Best Practices – CSS Stylesheet Formatting

Question by Justin Niessner

This may seem like a strange question…but here goes:

I’m currently working on creating a fairly large site using table-less design/css (obviously the best way to go). Unfortunately, I have a requirement that is completely out of my control that states I must have only one stylesheet for the site.

In some regards this is better because it forces me to think about style re-use pro-actively while designed the pages. On the other hand…the stylesheet is becoming monolithic and I’m quickly losing myself trying to find styles I know I’ve already defined.

I’d like to do myself (and anybody who has to work on the site in the future) a favor and make the CSS as readable and easy to update as possible. That’s where you come in. I’m looking for formatting/organizational suggestions/best practices.

Somebody out there has to be better at it than I am.

Answer by Hexxagonal

Why not have multiple stylesheets on your development boxes, but have them merged into one in your deploy scripts.

Answer by Starx

I seem to have a different type of CSS Coding Style. I tend to apply a pattern similar to programming.

Here is a sample markup and the way I style them.

<div id="menubar">
   <ul>
      <li>
        <a href="#">Test</a>
      </li>
   <ul>
</div>

<div id="footerMenubar">
   <ul>
      <li>
        <a href="#">Test</a>
      </li>
   <ul>
</div>

CSS

html {}
    body {}

   #menubar {}
      #menubar ul {}
          #menubar ul li {}
              #menubar ul li a {}


   #footerMenubar {}
      #footerMenubar ul {}
          #footerMenubar ul li {}
              #footerMenubar ul li a {}

Of course, some of you will raise a topic about the file size, but I gain much more efficiency and readability using this pattern that I am willing to compromise a little bit of file size. Furthermore, it also gives a idea of the position where a particular markup lies in the HTML file also.

(P.S, Same answer can be found here too.

Read more
April 22, 2011

Show a div when a mouseover on a link

Question by Pandu

If I mouseover on a link it has to show div.

My problem is that I have to show divs in all of the links inside a page. For each link I have to show a different div.

How to do this using javascript?

Answer by Starx

Since, your question does not specify anything. I will give a simplest solution I can. That is, with plain CSS, no JS needed.

Here is a demo

Markup

<a href="#">
    Some
    <div class="toshow">
        Hello
    </div>
</a>
<a href="#">
    None
    <div class="toshow">
        Hi
    </div>
</a>

CSS

.toshow { 
    display:none; 
    position: absolute; 
    background: #f00; 
    width: 200px; 
}
a:hover div.toshow { 
    display:block; 
}

You should not try to rely on script as much as possible. This is a very simple example, with displays the use of :hover event of the link.

Read more
April 21, 2011

call jquery function from server

Question by user321963

In asp.net, How can i trigger client side jquery event from server. I want to implement it in my chat section… current the chat seems to work fine… but it has one problem… i have to send a request every 5 seconds from client’s browser to the his chat history.. which i feel is not a good idea…

can anyone provide any solution for my problem

Answer by Starx

Although, I am not that skilled in ASP.Net, this problem can be solved in another way.

Have the server return the name of function you need to execute, then call it in the callback function?

Kinda like this (It is just a typo but)

$.post("yourpage.aspx",
   {
      d1: "v1"
   },
   function(data) {
     //now the data will hold the name of the function
     window[data](); 
   }
);

Now you can wrap the above code, in the another function, and set up a timer, to check for the response regularly, and execute the function if a condition is matched.

P.S. I have skipped the part, where the scripts check if the condition is matched.

Read more
April 19, 2011

PHP: Display the first 500 characters of HTML

Question by Vin

I have a huge HTML code in a php variable like :

$html_code = '<div class="contianer" style="text-align:center;">The Sameple text.</div><br><span>Another sample text.</span>....';

I want to display only first 500 characters of this code. This character count must consider the text in HTML tags and should exclude HTMl tags and attributes while measuring the length.
but while triming the code, it should not affect DOM structure of HTML code.

How can i do it in PHP?
Is there any tuorial or working examples available?
Kindly help!!

Answer by Starx

If its the text you want, you can do this with the following too

substr(strip_tags($html_code),0,500);
Read more

Best way to do a horizontal scrolling pane in jQuery?

Question by CaptSaltyJack

I came up with the solution below. It works great, but I’m curious to know if there’s a more efficient way of doing it. Thanks!

HTML:

<div id="magic-pane" style="width: 300px; height: 400px; background: #eee; overflow: hidden">
    <div id="scroller" style="width: 600px; height: 100%; left: 0px; position: relative">
        <div id="pane1" style="width: 300px; height: 100%; background: #efe; float: left">
            <span id="pane1-clicker">Whee, click me!</span>
        </div>
        <div id="pane2" style="width: 300px; height: 100%; background: #fee; float: left">
            <span id="pane2-clicker">Whoosh! Click me!</span>
        </div>
    </div>
</div>

Script:

$(document).ready(function() {
    $('#pane1-clicker').click(function() {
        $('#scroller').animate({ left: '-300px' }, 500);
    });
    $('#pane2-clicker').click(function() {
        $('#scroller').animate({ left: '0' }, 500);
    });
});

So basically, the magic-pane is a small viewport that’s 300px wide. Inside it is a scroller that’s twice as wide and contains two divs side-by-side. Pretty simple, but again, just wondering if there’s a more efficient way of coding this.

Demo

Answer by Starx

When the number are minimum, you do not need to worry about anything. Like in you case, 2 is pretty manageable. Note: that you are writing separate onClick function for all the pane, which will create problem.

But as the number grow, lets say 50, then you will have to write different onClick functions of $('#pane1-clicker') …. $("#pane50-clicker), which is highly inefficient. You should modify your script, to support any number of panes, without writing extra codes.

  • Also, extend the function, so that it can be used as plugin.
  • It would be better if the plugin could match a particular selector and assign the related positions like left:300px
Read more
April 18, 2011

Copy certain text from one div into another div

Question by Paul

I want to be able to copy certain text from one div into another div.

The text is generated from a WordPress Plugin, and it generates 2 different divs, with the following classes 1 called .voting inactive and the second one called .voting.

The text generated is rating based is it will look something like: Rating 4.5/5, i ONLY want to take the 4.5 or whatever vote is generated and copy that into a div to display the result nicely.

Any help would be great.

Answer by Starx

An example

HTML

<div id="this">Sometext</div>
<div id="that"></div>

Script

$(document).ready(funtion() {
   $("#that").html($("#this").html());
});
Read more

How to limit browse button to valid image files only

Question by sandeep

I want that whenever we click on browser button to upload so only image file is comes automatically instead of other file extension

Answer by Starx

You cannot restrict the upload, with just using HTML. There are two ways AFAIK

  • Read the file types and deny, after the form is submitted at the back end.
  • Use plugins like uploadify to restrict while selecting the file
Read more

Adding submit event on form prevents submit parameter from being included in HTTP POST

Question by Andy

Just what the question title says. I’m using SpringMVC, but that’s irrelevant really. I just need to be able to pass the submit button name=value along with the rest of the form parameters for validation and control purposes. Example below for clarification:

The HTML I’m using:

<form action='somepage.htm' method='post'>
  <input name='somename' value='bob' />
  <input type='submit' name='mybutton' value='click me' />
</form>

The JavaScript (with jQuery) I’m using:

$('form').submit(function() {
  $('input[type="submit"]', this).attr('disabled','disabled');
  return true;
}

And so the HTTP POST request looks like this without the JavaScript event binding:

somepage.htm?somename=bob&mybutton=click%20me

And with the bound event, it excludes the button parameter as such:

somepage.htm?somename=bob

I need to be able to disable the buttons and still send the button value to the server for processing.

Thanks!

SOLUTION:

The code I actually used to solve this problem is:

$(document).ready(function() {
  $('input[type="submit"]').click(function() {
    var clone = $(this).clone();
    $(clone).attr("type","hidden");
    $(this).attr('disabled','disabled');
    $(clone).appendTo($(this).parents('form')[0]);
    return true;
  });
});

And in case anyone was wondering, pressing Enter on a field in the form does in fact trigger the click event on the first submit button in the form!

Answer by Chris

Disabled inputs cannot be submitted.

http://www.w3.org/TR/html4/interact/forms.html#h-17.12

So maybe the way to go is to add a hidden element <input type='hidden' value='foo' name='bar'/> to stimulate the validation methods on the other end.

Answer by Starx

I think, if the submit button is clicked, then it’s values will also be submitted, like rest of the form.

Read more
...

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