hide one div when another is showing in jQuery? - javascript

I am trying to hide a div when another one is visible.
I have div 1 and div 2.
If div 2 is showing then div 1 should hide and if div 2 is not showing then div 1 should be visible/unhide.
The function would need to be function/document ready upon page load.
I've tried this but I'm not having any luck, can someone please show me how I can do this.
<script>
window.onLoad(function () {
if ($('.div2').is(":visible")) {
$(".div1").fadeOut(fast);
} else if ($('.div2').is(":hidden")) {
$('.div1').fadeIn(fast);
}
});
</script>

Add a class of hidden to each div, then toggle between that class using jQuery. By the way, window.onload is not a function, it expects a string like window.onload = function() {}. Also, put fast in quotations. I don't know if that's required, but that's how jQuery says to do it.
<div class="div1"></div>
<div class="div2 hidden"></div>
.hidden { display: none }
$(document).ready(function() {
if($(".div1").hasClass("hidden")) {
$(".div2").fadeIn("fast");
}
else if($(".div2").hasClass("hidden")) {
$(".div1").fadeIn("fast");
}
});

You should pass a string to the .fadeIn() and .fadeOut() methods.
Instead of .fadeIn(fast) it'll be .fadeIn("fast"). Same for .fadeOut().
And in general since you're already using jQuery it's better to wrap your code like this:
$(function () {
// Code goes here
});

It looks like you're using jquery selectors (a javascript library). If you're going to use jquery make sure the library is loaded properly by including it in the document header (google makes this easy by hosting it for you <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>)
With jQuery loaded you can do it like this
$(document).ready(function(){
if ($('.div1').is(":visible")) {
$('div2').hide();
}
else if ($('.div2').is(":visible")) {
$('div1').hide();
}
});
WORKING EXAMPLE: http://jsfiddle.net/HVDHC/ - just change display:none from div 2 to div 1 and click 'run' to see it alternate.

You can use setTimeout or setInterval to track if these divs exists
$(function() {
var interval = window.setInterval(function() {
if($('#div2').hasClass('showing')) {
$('#div1').fadeOut('fast');
}
if($('#div2').hasClass('hidden')) {
$('#div1').fadeIn('fast');
}
}, 100);
// when some time u don't want to track it
// window.clearInterval(interval)
})
for better performance
var div1 = $('#div1')
, div2 = $('#div2')
var interval ....
// same as pre code

Related

jquery div hide not working on first load

I am using remote javascripts to populate two divs on my site.
<div id="flix-inpage"></div>
<div id="ccs-inline-content"></div>
i am using the following code to display only one div if content is available on both divs. I have added this code to the bottom of the page:
$(document).ready(function(){
setTimeout(function() {
if ($("#flix-inpage #inpage_responsive").length > 0) {
$("#ccs-inline-content").hide();
} else {
$("#ccs-inline-content").show();
return false;
}
}, 2000);
});
I have specified a css class:
#ccs-inline-content{
display: none;
}
If Both DIV have same content
The problem I am having is that #ccs-inline-content is not hiding on first load. If I reload the page couple of times then #ccs-inline-content - hide() kicks in otherwise the content is visible.
I have tried different browser but same result.
i test this code , but good working . just i add .text() function in this code
$(document).ready(function(){
setTimeout(function() {
if ($("#flix-inpage").text().length <= 0 ) {
$("#ccs-inline-content").show();
} else {
$("#ccs-inline-content").hide();
}
}, 2000);
});
#ccs-inline-content{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="flix-inpage">12</div>
<div id="ccs-inline-content">ok</div>
If I understand correctly, you want #flix-inpage to be shown and #ccs-inline-content to be hidden unless #flix-inpage is empty. This would do the job:
$(document).ready(function() {
if ($("#flix-inpage").children().length) {
$("#ccs-inline-content").hide();
} else {
$("#ccs-inline-content").show();
}
});
You need to make sure the other scripts you mentioned finish before this runs, So put this somewhere after you execute the other two, at the bottom of the <body> tag.

How do I apply jQuery's slideToggle() to $(this) and do the opposite to all other elements?

What I'd like to do is have all elements of class collapsible_list not displayed by default (with one exception... see below*), and then toggle their display when their parent <div class="tab_box"> is clicked. During the same click, I'd also like for every other element of class collapsible_list to be hidden so that only one of them is expanded at any given time.
*Furthermore, when the page initially loads I'd also like to check to see if an element of collapsible_list has a child a element whose class is activelink, and if there is one then I'd like that link's parent collapsible_list element to be the one that's expanded by default.
Here's some sample html code:
<style>
.collapsible_list {
display: none;
}
.collapsible_list.active {
display: block;
}
</style>
<div id="sidebar">
<div class="tab_box">
<div class="collapsible_tab">2014</div>
<div class="collapsible_list panel-2014">
1
2
3
</div>
</div>
<div class="tab_box">
<div class="collapsible_tab">2013</div>
<div class="collapsible_list panel-2013">
<a class="activelink" href="/2013/1">1</a>
2
3
</div>
</div>
</div>
And here's where I'm currently at with the javascript (although I've tried a bunch of different ways and none have worked like I'd like them to):
$(document).ready(function() {
// This looks redundant to me but I'm not sure how else to go about it.
$(".collapsible_list").children("a.activelink").parent(".collapsible_list:not(.active)").addClass("active");
$(".tab_box").click(function() {
$(this).children(".collapsible_list").toggleClass("active").slideToggle("slow", function() {
$(".collapsible_list.active:not(this)").each(function() {
$(this).slideToggle("slow");
});
});
});
});
I hope that's not too confusing, but if it is then feel free to let me know. Any help is much appreciated.
Since you have a dom element reference that needs to be excluded use .not() instead of the :not() selector
jQuery(function ($) {
// This looks redundant to me but I'm not sure how else to go about it.
$(".collapsible_list").children("a.activelink").parent(".collapsible_list:not(.active)").addClass("active").show();
$(".tab_box").click(function () {
var $target = $(this).children(".collapsible_list").toggleClass("active").stop(true).slideToggle("slow");
//slidup others
$(".collapsible_list.active").not($target).stop(true).slideUp("slow").removeClass('active');
});
});
Also, instead of using the slide callback do it directly in the callback so that both the animations can run simultaniously
Also remove the css rule .collapsible_list.active as the display is controlled by animations(slide)
Try This.
$('.collapsible_tab a').on('click', function(e){
e.preventDefault();
$('.collapsible_list').removeClass('active')
$(this).parent().next('.collapsible_list').toggleClass('active');
});
Fiddle Demo
I think your code would be less complicated if you simply remembered the previously opened list:
jQuery(function($) {
// remember current list and make it visible
var $current = $('.collapsible_list:has(.activelink)').show();
$(".tab_box").on('click', function() {
var $previous = $current;
// open new list
$current = $('.collapsible_list', this)
.slideToggle("slow", function() {
// and slide out the previous
$previous.slideToggle('slow');
});
});
});
Demo

Swap two divs with a same class

I am sort-of stuck with this minor part and I can't move on with my project.
Basically what I am trying to do is to fadeIn/fadeOut between two divs with same class, but keep the function as short as possible.
I have made following but apparently it will work only if both divs are hidden in the begginging and I need to show default title (first div) on load and after 2 seconds I want to swap to another title and then it will keep going circular.
HTML:
<div class="ref-title">Sample Title #1</div>
<div class="ref-title">Sample Title #2</div>
JS:
function titleSwap () {
$('.ref-title:hidden:first').fadeIn(500).delay(2000).fadeOut(500, function () {
$(this).appendTo($(this).parent());
titleSwap();
});
} titleSwap();
CSS:
.ref-title {
display: none;
}
JS Fiddle Demo
So I need first div displayed as block and then it will disappear and the other one will appear and keep going on like that... Any tips ?
JSFiddle - Adding a hidden class to the div you want to start as hidden and then changing the function as below should work.
HTML
<div class="ref-title">Sample Title #1</div>
<div class="ref-title hidden">Sample Title #2</div>
CSS
.hidden {
display: none;
}
JS
(function titleSwap() {
$('.ref-title').not('.hidden').delay(2000).fadeOut(500, function () {
var $me = $(this);
$('.ref-title.hidden').removeClass('.hidden').hide().fadeIn(500, function () {
$(this).removeClass('hidden');
$me.addClass('hidden');
titleSwap();
});
});
})();
Additionally, if you don't want to include the hidden class on the DIV within the mark-up you can just use $('.ref-title:nth-child(2)').addClass('hidden'); before the titleSwap function to add the class to the second DIV.
If you can use just show/hide you can try like this: show/hide Example
function toggleTitle() {
$('header > h2').delay(2000).toggle('fast', function () {
toggleTitle();
});
}
If you must use fadeIn/fadeOut its a bit more complicated due to the concurrent fade effect between the titles... this is my solution fadeIn/Out Example
function toggleTitle() {
var visible = $('header > h2:visible');
var hidden = $('header > h2:hidden');
visible.delay(2000).fadeToggle('fast', function () {
hidden.fadeToggle('fast');
toggleTitle();
});
}
it's easy if you put ID's on them, is this posible? check out this answer
jQuery fadeOut one div, fadeIn another on its place
$('#fadeout').fadeOut(300);
$('#fadein').delay(2000).fadeIn(300);
if you cannot add IDs, try this. it assumes they are the only elements under their immediate parent
$('.ref-title:first-child').fadeOut(300);
$('.ref-title:last-child').delay(2000).fadeIn(300);

how to repeat same Javascript code over multiple html elements

Note: Changed code so that images and texts are links.
Basically, I have 3 pictures all with the same class, different ID. I have a javascript code which I want to apply to all three pictures, except, the code needs to be SLIGHTLY different depending on the picture. Here is the html:
<div class=column1of4>
<img src="images/actual.jpg" id="first">
<div id="firsttext" class="spanlink"><p>lots of text</p></div>
</div>
<div class=column1of4>
<img src="images/fake.jpg" id="second">
<div id="moretext" class="spanlink"><p>more text</p></div>
</div>
<div class=column1of4>
<img src="images/real.jpg" id="eighth">
<div id="evenmoretext" class="spanlink"><p>even more text</p></div>
</div>
Here is the Javascript for the id="firsttext":
$('#firstextt').hide();
$('#first, #firsttext').hover(function(){
//in
$('#firsttext').show();
},function(){
//out
$('#firsttext').hide();
});
So when a user hovers over #first, #firsttext will appear. Then, I want it so that when a user hovers over #second, #moretext should appear, etc.
I've done programming in Python, I created a sudo code and basically it is this.
text = [#firsttext, #moretext, #evenmoretext]
picture = [#first, #second, #eighth]
for number in range.len(text) //over here, basically find out how many elements are in text
$('text[number]').hide();
$('text[number], picture[number]').hover(function(){
//in
$('text[number]').show();
},function(){
//out
$('text[number]').hide();
});
The syntax is probably way off, but that's just the sudo code. Can anyone help me make the actual Javascript code for it?
try this
$(".column1of4").hover(function(){
$(".spanlink").hide();
$(this).find(".spanlink").show();
});
Why not
$('.spanlink').hide();
$('.column1of4').hover(
function() {
// in
$(this).children('.spanlink').show();
},
function() {
// out
$(this).children('.spanlink').hide();
}
);
It doesn't even need the ids.
You can do it :
$('.column1of4').click(function(){
$(this); // the current object
$(this).children('img'); // img in the current object
});
or a loop :
$('.column1of4').each(function(){
...
});
Dont use Id as $('#id') for multiple events, use a .class or an [attribute] do this.
If you're using jQuery, this is quite easy to accomplish:
$('.column1of4 .spanlink').hide();
$('.column1of4 img').mouseenter(function(e){
e.stopPropagation();
$(this).parent().find('.spanlink').show();
});
$('.column1of4 img').mouseleave(function(e){
e.stopPropagation();
$(this).parent().find('.spanlink').hide();
});
Depending on your markup structure, you could use DOM traversing functions like .filter(), .find(), .next() to get to your selected node.
$(".column1of4").hover(function(){
$(".spanlink").hide();
$(this).find(".spanlink, img").show();
});
So, the way you would do this, given your html would look like:
$('.column1of4').on('mouseenter mouseleave', 'img, .spanlink', function(ev) {
$(ev.delegateTarget).find('.spanlink').toggle(ev.type === 'mouseenter');
}).find('.spanlink').hide();
But building on what you have:
var text = ['#firsttext', '#moretext', '#evenmoretext'];
var picture = ['#first', '#second', '#third'];
This is a traditional loop using a closure (it's better to define the function outside of the loop, but I'm going to leave it there for this):
// You could also do var length = text.length and replace the "3"
for ( var i = 0; i < 3; ++i ) {
// create a closure so that i isn't incremented when the event happens.
(function(i) {
$(text[i]).hide();
$([text[i], picture[i]].join(',')).hover(function() {
$(text[i]).show();
}, function() {
$(text[i]).hide();
});
})(i);
}
And the following is using $.each to iterate over the group.
$.each(text, function(i) {
$(text[i]).hide();
$([text[i], picture[i]].join(', ')).hover(function() {
$(text[i]).show();
}, function() {
$(text[i]).hide();
});
});
Here's a fiddle with all three versions. Just uncomment the one you want to test and give it a go.
I moved the image inside the div and used this code, a working example:
$('.column1of4').each(function(){
$('div', $(this)).each(function(){
$(this).hover(
function(){
//in
$('img', $(this)).show();
},
function(){
//out
$('img', $(this)).hide();
});
});
});
The general idea is 1) use a selector that isn't an ID so I can iterate over several elements without worrying if future elements will be added later 2) locate the div to hide/show based on location relational to $(this) (will only work if you repeat this structure in your markup) 3) move the image tag inside the div (if you don't, then the hover gets a little spazzy because the positioned is changed when the image is shown, therefore affecting whether the cursor is inside the div or not.
EDIT
Updated fiddle for additional requirements (see comments).

make div text disappear after 5 seconds using jquery?

i need to make a div text disappear after x seconds of displaying it using an ajax call
can you help me on this please ?
thanks
You can use empty() to remove a <div> contents:
setTimeout(fade_out, 5000);
function fade_out() {
$("#mydiv").fadeOut().empty();
}
assuming:
<div id="mydiv">
...
</div>
You can do this with an anonymous function if you prefer:
setTimeout(function() {
$("#mydiv").fadeOut().empty();
}, 5000);
or even:
var fade_out = function() {
$("#mydiv").fadeOut().empty();
}
setTimeout(fade_out, 5000);
The latter is sometimes preferred because it pollutes the global namespace less.
You can try the .delay()
$(".formSentMsg").delay(3200).fadeOut(300);
call the div set the delay time in milliseconds and set the property you want to change, in this case I used .fadeOut() so it could be animated, but you can use .hide() as well.
http://api.jquery.com/delay/
$.doTimeout( 5000, function(){
// hide the div
});
You would need to set something like setTimeout('$("#id").fadeOut("slow")', 5000) but other than that it depends on what the rest of your code looks like
This should work:
$(document).ready(function() {
$.doTimeout(5000, function() {
$('#mydiv').fadeOut();
});
});
You may need to display div text again after it has disappeared.
This can be done in 1 line.
$('#div_id').empty().show().html(message).delay(3000).fadeOut(300);
This Answer is without jQuery, you can just grab your element and know its index position.
Then use it in the div below. I will be your div's index number in dom.
const div = document.querySelectorAll('div');
setTimeout(() => {
div[i].textContent = '';
}, 3000);

Categories

Resources