Category: jQuery


This was really annoying me as I found a nice lib which worked called jquery-outside-events , which I forked onto my own Github (could be tidier/easier imho) but it wouldn’t work! The reason I think was possibly it was conflicting with Prototype JS, which Magento uses.

The $ symbol is reserved for Prototype so I found I had to replace $(‘#etc’); with jQuery(‘#etc’); Since doing that however I’ve discovered you can call $j instead of $ or jQuery.

Anyway! Here’s the code you need:

$j('body').click(function (event)
{
    element = $j(event.target);
    if(element.parents('.skip-link.skip-cart').length == 1 || element.hasClass('skip-cart'))
    {
        return;
    }
    var parent = $j('.minicart-wrapper').parents('.skip-content');
    var link = parent.siblings('.skip-link');

    if (element.parents('.minicart-wrapper').length == 0) {
        parent.removeClass('skip-active');
        link.removeClass('skip-active');
    }
});

Now when you click show basket, the basket appears, but you can now click elsewhere on the page to make it close again!

Advertisements

Ever seen that message? I have, but thought I’d let you know what’s going on, as I just encountered it again in a Magento site I’m working on in my new workplace.

When this happens, it’s usually because of a clash between some other javascript library that uses the $ symbol. In Magento’s case, that’s Prototype JS (http://prototypejs.org/).

To sort it, you just need to replace all your $’s with jQuery, like so:

jQuery(document).ready(function(){
    // etc
});

You can also say var $j = jQuery, then use $j(‘#id’); instead 😀

If you’re here, that’s probably because you just put a datepicker into a bootstrap modal, but realised that the Year dropdown isn’t working properly, and when you click it, nothing appears to happen.

Luckily, it’s quite easy to fix. After initialising your element with

$('#mytextbox').datepicker({//options here});

All that is required is to paste this line of code, which does something regarding javascript’s dom focus :

$.fn.modal.Constructor.prototype.enforceFocus = function() {}

Job done! You can get back on with your work now! 🙂

If you have ever done any stuff with jquery/javascript that redirects you upon submitting a form, you’ll have noticed that the return key slips through the net and doesn’t obviously trigger the click event.
I’ve dealt with this nonsense plenty of times but i always end up hunting through my code to find it again. So to spare my sanity, I’m putting it here!

$('#submit').click(function(e){
 e.preventDefault();
 var name = $('#search').val();
 window.location.href = '/some/url/'+name;
 });
$("#search").keyup(function(event){
 if(event.keyCode == 13){
 $("#submit").click();
 }
 });

Just some quick notes.
Firstly, don’t give your customers all those buttons! They will end up breaking something!
Secondly, although they bang on about a jQuery version, I just could not get it to work!
Probably the most important factor here is adding images etc. Without buying some $50 plugin, its actually one line of code!
Anyway, here’s a typical setup from one of my sites:

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

$(document).ready(function() {
tinyMCE.init({
plugins : '-example', // - tells TinyMCE to skip the loading of the plugin
    mode : "textareas",
    theme : "advanced",
    theme_advanced_blockformats : "p,div,h1,h2,h3,h4,h5,h6,blockquote,dt,dd,code,samp",
    theme_advanced_buttons1 : "image, bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,undo,redo,link,unlink,formatselect,code",
    theme_advanced_buttons2 : "",
    theme_advanced_buttons3 : "",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    theme_advanced_statusbar_location : "bottom",
 editor_encoding: "raw",
    remove_linebreaks : false,
    convert_newlines_to_brs : true

// Example content CSS (should be your site CSS)
content_css : "css/style.css",

});

//adding your images ionto the tinmce window
$('#click').click(function(){
img = '<img src="http://your/url/to/image.jpg" />';
tinyMCE.execCommand('mceInsertContent',false,img);
});
});
</script>

Ever made a jquery slider only to find that when you mouse over your menu items quickly you need to wait until it all catches up with itself? you need to .stop()!

<ul id="nav">
<li>
<a href="/about/opening-times">About Us</a>
<ul class="submenu" style="display: none;">
<li><a href="/about/opening-times">Opening Times</a></li>
<li><a href="/about/key-people">Key People</a></li>
<li><a href="/about/awards">Awards</a></li>
</ul>
</li>
<li>
<a href="/our-tea/list">Our Tea</a>
<ul class="submenu" style="display: none;">
<li><a href="/our-tea/list">List of our teas</a></li>
<li><a href="/our-tea/tea-guild">Information on the tea guild</a></li>
<li><a href="/our-tea/info">Information on purchase of tea</a></li>
</ul>
</li>
<li><a href="/menus">Menus</a></li>
<li>
<a href="/afternoon-tea/history">Afternoon Tea</a>
<ul class="submenu" style="display: none;">
<li><a href="/afternoon-tea/history">History of afternoon tea</a></li>
<li><a href="/afternoon-tea/our-offerings">Our offerings</a></li>
<li><a href="/afternoon-tea/menus">Menus</a></li>
</ul>
</li>
<li><a href="/events">Events</a></li>
<li><a href="/gallery">Gallery</a></li>
<li><a href="/private-hire">Private Hire</a></li>
<li><a href="/testimonials">Testimonials</a></li>
</ul>
<script type="text/javascript">
$(document).ready(function(){
$('ul#nav li').hover(function()
{
$(this).find('ul.submenu').stop(true, true).slideDown('slow'); }, 
function() {$(this).parent().find('ul.submenu').stop(true, true).slideUp('slow');
});
});
</script>

And that should take care of it!

Custom jQuery validator functions

The jQuery validator is really cool, and you can create your own validators. Here’s one that counts the words in a text area, and validates :

$('.word_count').each(function() {
 var input = '#' + this.id;
 var count = input + '_count';
 console.log(input);
 console.log(count);
 $(count).show();
 word_count(input, count);
 $(this).keyup(function() { word_count(input, count) });
 });
function word_count(field, count) {
var number = 0;
 var matches = $(field).val().match(/\b/g);
 if(matches) {
 number = matches.length/2;
 }
 $(count).text( number);
 }
jQuery.validator.addMethod("twentywords", function(value, element, param) { 
 if($(element+'_count').html() > 19){return true;}
 else{return false;}
 }, jQuery.validator.messages.url);

And in the rules section:

rules: {
f_review: {
 twentywords: true
 }
 },
 messages: {
f_review: "Please leave a review of the agent at least 20 words"
 }

I’ve hard coded the name input into the validator, as I’m in work and it needs done quickly, but I’m sure this could be tweaked. Finally there is a hidden element that the word cound gets stored in and the input textarea has a class of word_count:

<div id="f_review_count"style="display:none"></div>
 <textarea name="f_review" id="f_review" rows="8" cols="40" class="text-long word_count"></textarea>

The word count stuff can be used on its own without the validator too. 🙂

Once again IE stops a developer in his tracks and forces him to rewrite something that works perfectly in every other browser. This time – disabling Return using jQuery.

This works for everyone except Microsofts (quirky) browser. More enamel is lost in a year through developers teeth grinding that I’m sure dental profits are soaring through the roof. Anyway:

$(window).keyup(function(e) 
{    
    if (e.keyCode == 13)
    { 
       e.preventDefault();         
        return false;
    }
});

Whereas this will work

$('#my-form').bind("keypress", function (e) {
    if (e.keyCode == 13) 
    {
        e.preventDefault();
        return false;
    }
});

Irritating. Boycott IE!

My shiny new website uses an awesome jquery tool called Coda Slider. It’s really good, but I kind of left the old fashioned people with a 1024×768 resolution behind, as my sites default width (and my slider image widths) are  1200px!

Anyway, I couldn’t have cared less, everyone uses a laptop or widescreen monitor anyway! Until that is the feedback started coming back. Looks like I need to fix this then :-s

First up, here’s the way the coda slider works:

<script src="/js/coda/jquery.coda-slider-3.0.min.js" type="text/javascript"></script>
 <link href="/js/coda/coda-slider.css" rel="stylesheet" />

..in the head, obviously. In your body, you set it out like this:

<div class="coda-slider-wrapper">
 <div class="coda-slider preload" id="coda-slider-1">
   <div class="panel">
     <div class="panel-wrapper">
       <img src="/img/coda/banner1.png" />
     </div>
   </div>
   <div class="panel imagepanel">
     <div class="panel-wrapper" style="text-align: center;">
       <img src="/img/coda/ddale.jpg" />
     </div>
     <div class="panel-wrapper" style="text-align: center;">
       <img src="/img/coda/let-your-property.png" />
     </div>
     <div class="panel-wrapper" style="text-align: center;">
       <img src="/img/coda/mobile.jpg" />
     </div>
   </div>
  </div>
 </div>

And in your <script> :

var slide = $('#coda-slider-1').codaSlider({
 autoHeight : false,
 autoSlide : true,
 dynamicArrows : false
 });

Now we have an awesome slider!

However, the guys with the 1024x768px monitors are crying in pain! So we can hack a quick fix for them:

if (screenwidth <= 1024) 
{
    $('div.panel-wrapper img').css('width','1000');
    $('.coda-slider-wrapper .coda-slider').css('width','1000');
    $('.coda-slider-wrapper .coda-slider').css('height','291');
    $('.coda-slider-wrapper .coda-slider .panel').css('width','1000');
}

That shrinks the image width and panel containers to fit 🙂 A bit hacky, but I still like it. Next time though, I’ll do my CSS in em’s and %ages!