Tuesday 15 May 2012

javascript - Responsive Jquery toggle command -



javascript - Responsive Jquery toggle command -

i having issue code. whenever, load page in browser or in mobile device, , seek toggle toggles multiple times when clicked on once. trying utilize syntax code create responsive.

my codepen

class="lang-js prettyprint-override">$(window).resize(function() { $(".textcontent").hide(); if ($(window).width() <= 480) { jquery(function($) { $(document).ready(function() { $(".textcontent").hide(); $(".titleheader").click(function() { $(this).toggleclass("active").next().slidetoggle("fast"); homecoming false; }); }); }); } });

the text toggles more 1 time because binding click handler each time resize event fires. each bind attaches handler so, depending on how many times resize event fires, might end many click handlers firing @ once.

i suggest bind or unbind click handler depending on screen width, so:

class="lang-js prettyprint-override">$(function() { // function toggle text section function toggletext(elm) { $(elm).toggleclass("active").next().slidetoggle("fast"); } // resize event handler $(window).on('resize', function() { if ($(window).width() <= 480) { // if window <= 480, unbind , rebind click handlers, , hide text content $(".titleheader").off('click').on('click', function() { toggletext(this); }); $(".textcontent").hide(); } else { // if window > 480, unbind click handlers , hide text $(".titleheader").off('click'); $(".textcontent").show(); } }).trigger('resize'); // initialize - trigger resize 1 time upon load });

working example

you might want throttle or "debounce" resize handler won't fire continuously in ie, safari, , chrome.

edit:

an alternate method set flag indicate whether layout "small" or "large". then, alter layout if flag not indicate desired layout:

$(function() { // layout flag (defaults "not small") var little = false; // function toggle text section function toggletext(elm) { $(elm).toggleclass("active").next().slidetoggle("fast"); } // resize event handler $(window).on('resize', function() { if ($(window).width() <= 480) { // if window <= 480 , layout "not small", bind click handlers , hide text content if (!small) { console.log('made small'); $(".titleheader").on('click', function() { toggletext(this); }); $(".textcontent").hide(); // set layout flag "small" little = true; } } else { // if window > 480 , layout "small", unbind click handlers , hide text if (small) { console.log('made large'); $(".titleheader").off('click'); $(".textcontent").show(); // set layout flag "not small" little = false; } } }).trigger('resize'); // initialize - trigger resize 1 time upon load });

working example

javascript jquery responsive-design

No comments:

Post a Comment