Category Archives: jQuery

[jQuery]jQuery.each( object, callback ) break or continue

ref. http://docs.jquery.com/Utilities/jQuery.each#objectcallback

If you wish to break the each() loop at a particular iteration you can do so by making your function return false. Returning non-false(true) is the same as a continue statement in a for loop, it will skip immediately to the next iteration.

 

var arr = [ "one", "two", "three", "four", "five" ];
$.each(arr, function(i) {
    if(arr[i] == 'three') {
        return true; //continue
    }
    alert(arr[i]);
});

==> alert one, two, four, five
$.each(arr, function(i) {
    if(arr[i] == 'three') {
        return false; //break
    }
    alert(arr[i]);
});

==> alert one, two

[Rails3]How to set blank date on jquery datepicker in rails

TypeError: Object [object Object] has no method ‘Datepicker’

ref. http://rubydoc.info/gems/jquery-rails/2.0.2/frames

== Append ‘//=require jquery-ui’ to application.js:

vi app/assets/javascripts/application.js

//= require jquery
//= require jquery_ujs
//= require_tree
//= require jquery-ui

== Set jQuery datepicker option ‘showOn’ to ‘button’ -> “datepicker({showOn:’button’})”

vi app/views/new.html.erb

<%= form_for(@wash) do |f| %>

<%#= f.date_select :stocked_on %>
<%= f.text_field :stocked_on, :size =>10 %>

<%= f.submit %>
<% end %>

<script type=”text/javascript”>
jQuery.noConflict();
jQuery(document).ready(function($){
$(“#wash_stocked_on”).datepicker({showOn:’button’});
});
</script>

[jQuery] Table cell selection

<html>
<head>
 <script src="jquery-1.7.2.js" type="text/javascript"></script> 
<script type="text/javascript" language="javascript">
$.noConflict();
(function($) {
	$(function(){

	var inputs = $('#invoice_table tr:gt(0) td.quantity input, #invoice_table tr:gt(0) td.rate input');
	var amount_inputs = $('#invoice_table tr:gt(0) td.amount input');
	var vat_inputs = $('#invoice_table tr:gt(0) td.vat input');
	var subtotal_inputs = $('#invoice_table tr:gt(0) td.subtotal input');
	
	inputs.change(function() {
		//alert('change');
		// Finding them this way purely so that we don't duplicate the code,
		// it would be faster to separate the inputs array into their type and bind the change appropriately.
		var qty = $(this).closest('tr').find('td.quantity input').val();
		var rate = $(this).closest('tr').find('td.rate input').val();
		var amount_input = $(this).closest('tr').find('td.amount input');
		var vat_input = $(this).closest('tr').find('td.vat input');
		var subtotal_input = $(this).closest('tr').find('td.subtotal input');
	
		var amount = qty * rate;
		var vat = amount / 100 * 20;
		var subtotal = amount + vat;
	
		amount_input.val(amount.toFixed(2));
		vat_input.val(vat.toFixed(2));
		subtotal_input.val(subtotal.toFixed(2));
	
		update_totals();
	});
	
	function update_totals() {
		var amttotal = 0;
		var vattotal = 0;
		var total = 0;
	
		$.each(amount_inputs, function(){
			var val = parseFloat($(this).val());
			amttotal +=  isNaN(val) ? 0: val;
				
		});
		$.each(vat_inputs, function(){
			var val = parseFloat($(this).val());
			vattotal +=  isNaN(val) ? 0: val;
		});
		$.each(subtotal_inputs, function(){
			var val = parseFloat($(this).val());
			total +=  isNaN(val) ? 0: val;
		});
	
		$("#total_amount").val(amttotal.toFixed(2));
		$("#total_vat").val(vattotal.toFixed(2));
		$("#grand_total").val(total.toFixed(2));
	}    
	});
})(jQuery); 
</script>
</head>
<body>
<table border="1" id="invoice_table">
    <tr><th>qty</th><th>rate</th><th>amount</th><th>vat</th><th>subtotal</th></tr>
    <tr>
        <td class="quantity"><input type="text"></td><td class="rate"><input type="text"></td>
        <td class="amount"><input type="text"></td><td  class="vat"><input type="text"></td><td class="subtotal"><input type="text"></td>
    </tr> 
    <tr>
        <td class="quantity"><input type="text" value="5"></td><td class="rate"><input type="text" value="10"></td>
        <td class="amount"><input type="text"></td><td  class="vat"><input type="text"></td><td class="subtotal"><input type="text"></td>
    </tr> 
</table>
<div>
Total Amount: <input type="text" value="" id="total_amount"><br/>
Total Vat: <input type="text" value="" id="total_vat"><br/>
Grand Total: <input type="text" value="" id="grand_total">
</div>

</body>
</html>    

[jQuery] jQuery – Prototype js 의 $ 변수 충돌 피하기

참조: http://api.jquery.com/jQuery.noConflict/

방법1) This technique is especially effective in conjunction with the .ready() method’s ability to alias the jQuery object, as within callback passed to .ready() we can use $ if we wish without fear of conflicts later:

<script type="text/javascript" src="other_lib.js"></script><script type="text/javascript" src="jquery.js"></script><script type="text/javascript">// <![CDATA[
  jQuery.noConflict();
  jQuery(document).ready(function($) {
    // Code that uses jQuery's $ can follow here.
  });
  // Code that uses other library's $ can follow here.
// ]]></script>

예제)

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script><script type="text/javascript">// <![CDATA[
  jQuery.noConflict();

  jQuery(document).ready(function($) {
    // Code that uses jQuery's $ can follow here.
    $("div p").show();
  });

  // Code that uses other library's $ can follow here.
  document.observe("dom:loaded", function(){
    $("content").style.display = "block";
    //$$('div#content').invoke('show');
  });
// ]]></script>

Relinquish jQuery’s control of the ‘$’ variable.

code using $ as alias to jQuery

방법2) Reverts the $ alias and then creates and executes a function to provide the $ as a jQuery alias inside the functions scope.

jQuery.noConflict();
(function($) {
  $(function() {
    // more code using $ as alias to jQuery
  });
})(jQuery);
// other code using $ as an alias to the other library

예제)

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script><script type="text/javascript">// <![CDATA[
  jQuery.noConflict();

  (function($) { 
    $(function() {
      // more code using $() as alias to jQuery
      $("div p").show();
    });
  })(jQuery);

  // other code using $() as an alias to the other library
  document.observe("dom:loaded", function(){
    $("content").style.display = "block";
  });
// ]]></script>

Relinquish jQuery’s control of the ‘$’ variable.

code using $ as alias to jQuery

[jQuery] Dropdown menu

<style>
#container {
  position: relative;
}

#menu {
  position: absolute;
  top: 0;
  right: 0;
}

#menu, #menu ul {
  padding: 0;
  margin: 0;
  list-style: none;
}

#menu li {
  float: left;
  background: #FFF;
}

#menu a {
  display: block;
  padding: 5px;
  width: 130px;
}

#menu li ul {
  position: absolute;
  left: -999em;
  width: 140px;
}

#menu li:hover ul, #menu li ul:hover {
  left:auto;
}

</style>

<ul id="menu">
    <li><a href="#">What's new?</a>
          <ul class="active">
            <li><a href="#">Weekly specials</a></li>
            <li><a href="#">Last night's pics!</a></li>
            <li><a href="#">Users' comments</a></li>
          </ul>

    </li>
    <li><a href="#">Member extras</a>
        <ul>
            <li><a href="#">Premium Celebrities</a></li>
            <li><a href="#">24-hour Surveillance</a></li>
        </ul>
    </li>

    <li><a href="#">About Us</a>
        <ul>
            <li><a href="#">Privacy Statement</a></li>
            <li><a href="#">Terms and Conditions</a></li>
            <li><a href="#">Contact Us</a></li>
        </ul>
    </li>
</ul>

<script>
$(document).ready(function(){
  $('#menu li ul').css({
    display: "none",
    left: "auto"
  });
  $('#menu li').hover(function() {
    $(this)
    .find('ul')
    .stop(true, true)
    .slideDown('fast');
  }, function() {
    $(this)
    .find('ul')
    .stop(true,true)
    .fadeOut('fast');
  });
}); 
</script>

[jQuery] Check all checkboxes

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style>
.inactive {
  color: #666666;
}
.submit {
  margin-top: 10px;
} 
</style>

<form action="">
  <div class="stats">
    <h2 class="title">Reason for Celebrity</h2>

    <input name="reason" type="checkbox" value="net" />Famous on the internet<br/>
    <input name="reason" type="checkbox" value="crim" />Committed a crime<br />
    <input name="reason" type="checkbox" value="model" />Dates a super model<br />
    <input name="reason" type="checkbox" value="tv" />Hosts a TV show<br />
    <input name="reason" type="checkbox" value="japan" />Big in Japan<br />
    <hr />

    <input class="check-all" name="reason" type="checkbox" /><span>Check all</span>
    <br/>
    <input type="submit" value="Submit" class="submit" />
  </div>
</form>      


<script>
$(document).ready(function(){
  $('.check-all:checkbox').change(function() {
    var group = ':checkbox[name=' + $(this).attr('name') + ']';
    $(group).attr('checked', $(this).attr('checked'));
  });
});
</script>

[jQuery] Advanced Tooltips

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<style>
span.tooltip {
  background: transparent url(sprite_tooltips.png) no-repeat scroll 0 0;
  font: 15px/2 normal Helvetica,Arial,Verdana,sans-serif;
  display: none;
  height: 60px;
  position: absolute;
  left: 0;
  top: 0;
  text-align: left;
  white-space: nowrap;
  width: 220px;
  z-index: 100;
}

span.tooltip span {
  display: inline-block;
  padding: 15px 0 0 12px;
}

span.tooltip.left {
  background-position: 100% 0;
}

span.tooltip.left span {
  padding: 15px 0 0 17px;
}

span.tooltip.above {
  background-position: 0 100%;
}

span.tooltip.above span {
  padding: 13px 0 0 12px;
}

span.tooltip.above.left {
  background-position: 100% 100%;
}

span.tooltip.above.left span {
  padding: 13px 0 0 17px;
}
</style>

<p>
  Welcome to <strong style="text-decoration: underline">Advanced Tooltips!<span class='tooltip'><span><a href='#'>Legal Disclaimer</a></span></span></strong> the planet's premier celebrity tracking and monitoring service. 
</p>

<script>
var TT = {
  delay: 600,
  
  setTips: function(){
    
    $('.tooltip').parent().hover(function(){
      // store the tooltip being hovered
      TT.current = $(this);
      TT.timer = setTimeout(function(){
        // find the tooltip, 
        TT.current.find(".tooltip").fadeIn('fast');
      }, TT.delay);
    }, function(){
      // on mouseout, clear timer and hide tooltip
      clearTimeout(TT.timer);
      $(this).find(".tooltip").fadeOut('fast');
    }).attr("title", ""); // clear the title to stop browser tooltips
    
    var screenWidth = $(window).width();
    var screenBottom = $(window).scrollTop() + $(window).height();
    
    $(".tooltip").each(function(){
      // grab the containing element
      $container = $(this).parent();
      
      // give it relative position if required
      if ($container.css("position") != 'absolute' 
          && $container.css("position") != "fixed") {
        $container.css({position: 'relative'});
      }
      
      var totalHeight = $container.height() + $(this).outerHeight();
      var width = $(this).outerWidth();
      var offset = $container.offset();
      
      // now we get the position the tip
      var top = $container.height(); // default placement
      var left = 0;
      
      // re-position if it's off the right of the screen
      if (offset.left + width > screenWidth) {
        left = 0 - width + 42;
        $(this).addClass('left');
      } else {
        $(this).removeClass('left');
      }
      
      // re-position if it's off the bottom of the screen
      if (offset.top + totalHeight > screenBottom) {
        top = 0 - $(this).outerHeight();
        $(this).addClass('above');
      } else {
        $(this).removeClass('above');
      }
      
      // finally set the css properties to position onscreen
      $(this).css({
        "top": top,
        "left": left
      });
    });
  }
}
  
$(document).ready(function() {
  TT.setTips();
});

$(window).resize(function(){
  TT.setTips();
});
</script>

[jQuery] simple tooltips

<style>
.tooltip {
  display: none;
  position: absolute;
  border: 1px solid #333;
  background-color: #ffed8a;
  padding: 2px 6px;
}

</style>
<ul>
 <li> <a href="#" class="location" title="Check out all the Celebs in LA this week!">Los Angeles</a></li>
 <li> <a href="#" class="location" title="Check out all the Celebs in New York this week!">New York</a></li>
</ul>

<script>
$(document).ready(function(){
  $('.location').hover(function(e){
    // Hover over code
    var titleText = $(this).attr('title');
    $(this)
      .data('tipText', titleText)
      .removeAttr('title');
      
    $('<p class="tooltip"></p>')
      .text(titleText)
      .appendTo('body')
      .css('top', (e.pageY - 10) + 'px')
      .css('left', (e.pageX + 20) + 'px')
      .fadeIn('slow');
  }, function() {
    // Hover out code
    $(this).attr('title', $(this).data('tipText'));
    $('.tooltip').remove();
  }).mousemove(function(e){
    // Mouse move code
    $('.tooltip')
      .css('top', (e.pageY - 10) + 'px')
      .css('left', (e.pageX + 20) + 'px');
  });
});
</script>

[jQuery] slideshow plugins: innerFade, cycle

참조:
* InnerFade plugin: http://medienfreunde.com/lab/innerfade/

* Cycle plugin: http://malsup.com/jquery/cycle/

InnerFade plugin

<style>
  #news {
    display: block;
    height: 70px;
  }
  #news ul {
    list-style-type: none;
  }
</style>

<div id="news">
  <h2>News</h2>
  <ul>
    <li><a href="#">Barron Von Jovi spotted ... </a></li>
    <li><a href="#">Mo'Fat signs up-and-coming rapper ... </a></li>
    <li><a href="#">Glendatronix rumored to be ... </a></li>
    <li><a href="#">Man claims to be Darth Fader's son ... </a></li>
  </ul>
</div>

<script>
  $('#news ul').innerfade({
    animationtype: 'slide',
    speed: 750,
    timeout: 2000,
    type: 'random'
  });

</script>

Cycle slideshow plugin

<div id="photos">
  <img alt="Glendatronix" src="../../images/glenda_200.jpg"/>
  <img alt="Darth Fader" src="../../images/fader_200.jpg" />
  <img alt="Beau Dandy" src="../../images/beau_200.jpg" />
  <img alt="Johnny Stardust" src="../../images/johnny_200.jpg" />
  <img alt="Mo' Fat" src="../../images/mofat_200.jpg" />
</div>


<script>
$(document).ready(function(){
  $('#photos').cycle({
    fx: 'scrollDown',
    speedIn: 2500,
    speedOut: 500,
    timeout: 0,
    next: '#photos'
  });
}); 
</script>

[jQuery] Fading slideshow

<style>
  #photos img {
    display: none;
  }
  #photos .show {
    display: inline;
  }
</style>

<div id="photos">
  <img alt="Glendatronix" class="show" src="../../images/glenda_200.jpg" />
  <img alt="Darth Fader" src="../../images/fader_200.jpg" />
  <img alt="Beau Dandy" src="../../images/beau_200.jpg" />
  <img alt="Johnny Stardust" src="../../images/johnny_200.jpg" />
  <img alt="Mo' Fat" src="../../images/mofat_200.jpg" />
</div>

<script>
  $(document).ready(function() {
    slideShow();
  });
  
  function slideShow() {
    var current = $('#photos .show');
    var next = current.next().length ? current.next() : current.parent().children(':first');
    current.hide().removeClass('show');
    next.fadeIn().addClass('show');
    
    setTimeout(slideShow, 3000);
  }

</script>