Window re-size event breaks toggle after resize - javascript

I am having an issue with the below code. I created a window re-size event for a toggle div. The purpose is so when on smaller devices the header will toggle the content, otherwise the content is just displayed as is. The issue I am having is when I refresh the page, it works perfect. The second I resize it and click to toggle, it causes some sort of recursive call 5 times, so it toggles back and forth 5 times. Any suggestions?
$(window).resize(function() {
if ($(window).width() > 767) {
$(".toggle" ).show();
}
else {
$(".toggle" ).hide();
$( ".opener" ).click(function() {
$(this).next('.toggle').slideToggle();
});
}
}).resize();

It is not recommendable to insert a click function inside a resize function, because you are adding click functions to the tag every time you resize. If you add an unbind to the "opener" before the click line it should work.
$(window).resize(function() {
if ($(window).width() > 767) {
$(".toggle" ).show();
}
else {
$(".toggle" ).hide();
$( ".opener" ).unbind("click");
$( ".opener" ).click(function() {
$(this).next('.toggle').slideToggle();
});
}
}).resize();

Related

using jquery contains to get an element and add class

I'm trying to create dynamic navigation. When the screen size is that of a phone I am using a bootstrap list group but when I resize it I am using nav pills. What I'm trying to do is capture the current element with the active class so that when I resize the window it will add the class 'active' to which ever tag contains the text saved in variable currentTab. Currently I know I'm entering the changeActive function and have the text but I can not get it to add the active class.
<div id='navigation'>
<div class="list-group">
About
Animals
Adoptly
Blog
Events
</div>
</div><!--End of navigation-->
Javascript
$( document ).ready(function() {
var listHTML = '<div class="list-group">AboutAnimalsAdoptlyBlogEvents</div>'
var pillsHTML ='<ul class="nav nav-pills"><li role="presentation" class="active">About</li><li role="presentation">Animals</li><li role="presentation">Adoptly</li><li role="presentation">Blog</li><li role="presentation">Events</li></ul>'
function checkWidth() {
var windowsize = $(window).width();
var current = document.getElementsByClassName('active');
var displayText = current[0].textContent;
if (windowsize > 425) {
//if the window is greater than 440px wide then turn on jScrollPane..
$( "#navigation" ).empty();
$( "#navigation" ).html(pillsHTML);
checkActive(displayText);
}
else
{
$( "#navigation" ).empty();
$( "#navigation" ).html(listHTML);
checkActive(displayText);
}
}
function checkActive(currentTab){
console.log(currentTab);
$('a:contains(currentTab)').addClass('active');
}
checkWidth();
// Bind event listener
$( window ).resize(checkWidth);
$('#navigation').on('click','.list-group-item',function(e){
var previous = $(this).closest(".list-group").children(".active");
previous.removeClass('active'); // previous list-item
$(e.target).addClass('active'); // activated list-item
});
});
I created a different solution other than using contains so I'm going to post it here so that people know I've moved on but if someone actually has a solution using contains I will check back to pick as solution.
function checkWidth() {
var windowsize = $(window).width();
var current = document.getElementsByClassName('active');
var displayText = current[0].textContent;
if (windowsize > 425) {
//if the window is greater than 440px wide then turn on jScrollPane..
$( "#navigation" ).empty();
$( "#navigation" ).html(pillsHTML);
checkActive(displayText,true);
}
else
{
$( "#navigation" ).empty();
$( "#navigation" ).html(listHTML);
checkActive(displayText,false);
}
}
function checkActive(currentTab, bool){
console.log(bool);
if(bool)
{
$('li').removeClass('active');
var element = document.getElementById(currentTab);
$(element).addClass('active');
}
else
{
$('.list-group-item').removeClass('active');
var element = document.getElementById(currentTab);
$(element).addClass('active');
}
}
I saw your code and i think there is a misunderstanding, you're using your functions just when the document is ready, so your function $( window ).resize() its running just one time (when the DOM loaded) even if you resize the windows the DOM don't will change since you reload the pages and in this moment your functions runs but at the same time your active element will lose and the page will select the default element, so i suggest use the function:
$( window ).resize(function() {
//console.log("window size"+$(window).width());
//Here your code that change each time that you resize your window
});
I guess you want to create a response design page which its even more simple just adding css and using bootstrap features, just combine #media(max-min width) and add a collapse boostrap, this is a clear example of that: http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_theme_band_complete&stacked=h

Having troubles with removing and reapearing html elements with jquery

Basically I want to slide down a element, then when the button is hit again I want it to slide up, empty the div, then slide down with the new results. I'v been trying to figure out how to do this for so long and I cant seem to get it working with jquery.
$(".search").on("click",function(){
$('.results').slideUp(500).empty().append("<p>Results</p>").hide().slideDown(500)
});
I understand this is kind of specific to my project kind of but I do feel others might find this useful
I'm not sure what exactly your problem is, but I think the slideUp animation is not shown in your example.
The slideUp method takes a second argument, which is the function callback. It is called when the slideUp action is finished. If you do the rest of your actions in this callback function, is guaranteed to be performed after the slideUp.
jQuery('#testbutton').on('click',function() {
$('#testlist').slideUp(500, function() {
$('#testlist').empty().append("<li>this is a test</li>").slideDown(500);
});
});
You can find a fully working example here:
https://jsfiddle.net/dxyybwyh/5/
I want to slide down a element, then when the button is hit again I
want it to slide up, empty the div, then slide down with the new
results.
It seems simple enough to me
let me know if you need anything more
$('#myButton').click(function () {
if ( $( ".myDiv" ).is( ":hidden" ) ) {
//show the div
$( ".myDiv" ).slideDown( "slow" );
//add content
$( ".myDiv" ).html("New Content")
} else {
//hide the div
$( ".myDiv" ).slideUp( "slow" );
//clear content
$( ".myDiv" ).html("");
}
});
http://codepen.io/Rohithzr/pen/jqmGXg
Updated the pen with append ability and more readability
$('#myButton').click(function () {
if ( $( ".myDiv" ).is( ":hidden" ) ) {
show();
} else {
hide();
clearContent();
appendContent("New Content");
}
});
function clearContent(){
//clear content
$( ".myDiv" ).html("");
}
function appendContent(content){
$( ".myDiv" ).html($( ".myDiv" ).html()+content);
}
function hide(){
//hide the div
$( ".myDiv" ).slideUp( "slow" );
}
function show(){
//show the div
$( ".myDiv" ).slideDown( "slow" );
}

Drop Down text won't come back up and won't recognize other instances

I used OnClick drop down text with JavaScript and HTML code to make the dropdown hidden div project.
But the problems are:
1 - It won't open divs separatelly, all of the "projects" are open at once;
2 - I won't come back up once I click it again.
I made another line of code to make it go up:
$(function() {
$(".project").on('click', function() {
$(this).parent().find('.details').slideDown();
});
$(".project").on('click', function() {
$(this).parent().find('.details').slideUp();
});
});
$(function() {
$(".project2").on('click', function() {
$(this).parent().find('.details').slideDown();
});
$(".project2").on('click', function() {
$(this).parent().find('.details').slideUp();
});
});
And so on... and it goes up as soon as I click it only once, like an animation. It won't stay down and THEN on the next click it goes back up. AND it still gets both down instead of each one separately.
You shouldn't use document.ready to often if isn't needed.
// Shorthand for $( document ).ready()
$(function() {
});
If you bind two events to an element, .. it will be executed if you don't stopPropergation or making "cases".
So you can check the visibility and decide what to do:
$( function () {
$("[class^='project']").on( 'click', function () {
var $details = $( this ).parent().find( '.details' );
if ($details.is(':visible'))
$( this ).parent().find( '.details' ).slideUp();
else
$( this ).parent().find( '.details' ).slideDown();
});
} );
https://jsfiddle.net/3738Lnmf/
edit:
slideToggle is more elegant :) #Diego López
$( function () {
$("[class^='project']").on( 'click', function () {
$(this).parent().find('.details').slideToggle();
});
} );
https://jsfiddle.net/3738Lnmf/1/
Use .slideToggle() if you want to toggle between show and hide the div elements
$(function() {
$(".project").on('click', function() {
$(this).parent().find('.details').slideToggle();
});
$(".project2").on('click', function() {
$(this).parent().find('.details').slideToggle();
});
});

Move content on window resize

I am using the following jQuery to move content from the top of the main content column in mobile view to the top of the sidebar when in desktop view.
if (ww >= 768) {
$( '#move-me' ).insertBefore($( '#top-widget' ) );
}
Here's a fiddle:
http://jsfiddle.net/richerimage/co6nw6va/1/
This works fine on page load, but I'd like the content to be able to move back and forth on window re-size
Like all things, I guess this is easy if you know how! :)
Any help is greatly appreciated
With thanks
Richard
p.s. also, is there a way to move the content to the top of the #sidebar without the need to reference the #top-widget?
Try this:
$( document ).ready(function() {
doThis();
});
$( window ).resize( function() {
doThis();
});
function doThis(){
var ww = document.body.clientWidth;
if (ww >= 768) {
$( '#move-me' ).insertBefore($( '#top-widget' ) );
}else{
$( '#move-me' ).insertBefore($( '.post_content' ) );
}
}
Check JSFiddle Demo
So you need to use resize event handler:
$( window ).resize( function() {
var ww = document.body.clientWidth;
if (ww >= 768) {
$( '#move-me' ).insertBefore($( '#top-widget' ) );
}
});
jsFiddle

Removing class and attr at certain width issues

So, I have a menu that drops down. After, 955 (desktop) width the dropdown menu stays open using javascript and I am unable to close it, which is what I want. This works great, so when on a tablet the menu is closed but can be opened upon click, again this is what I want.
The problem occurs when I manually resize my screen width on desktop to tablet view, although its below 955 the menu stays open and I cant shut it. Please see this bootply example: http://bootply.com/86605
function checkWidth(init) {
if ($(window).width() > 955) {
$( "li#add" ).addClass( "open" );
$('#remove').removeAttr("data-toggle");
}
}
$(document).ready(function() {
checkWidth(true);
$(window).resize(function() {
checkWidth(false);
});
});
Im not sure what the 'init' argument is for as it appears to be doing nothing but you need to add an another condition and remove the 'open' class.
function checkWidth(init) {
if ($(window).width() > 955) {
$( "li#add" ).addClass( "open" );
$('#remove').removeAttr("data-toggle");
} else if($(window).width() < 955) {
$( "li#add" ).removeClass( "open" );
}
}
function checkWidth() {
if ($(window).width() > 955) {
$("li#add").addClass("open");
$('#remove').removeAttr("data-toggle");
} else if ($(window).width() < 955) {
$("li#add").removeClass("open");
$('#remove').attr("data-toggle","dropdown");
}
}
function checkWidth(init)
{/*If browser resized, check width again */
if ($(window).width() < 640) {
$('.second_menu_mid').addClass('rmm');
}else {if (!init) { $('.second_menu_mid').removeClass('rmm');
} }}
$(document).ready(function() {
checkWidth(true);
$(window).resize(function() {
checkWidth(false);
});});

Categories

Resources