Why doesn't my <div> slide with these jquery code? - javascript

I want to reduce my <div> size when I click on a <a> . But it doesn t work.
Javascript code
(divheight is a global variable)
function jamsho(id) {
var idd=id.substr(1);
alert(document.getElementById(idd).style.height);
if(document.getElementById(idd).style.height != 30) {
$(id).stop().animate({height:30}, 700);
divheight=document.getElementById(idd).style.height;
} else if (document.getElementById(idd).style.height == "30px") {
$(id).animate({height:divheight}, 700);
}
}
And call the function :
<div class="linkbox" id="linksbox">
<a id="Titr" onClick="jamsho('#linksbox')"> پیوند ها</a>
سایت روان آنلاین
</div>

ditch the onclick, ditch the vanilla js. It's as simple as follows:
jsFiddle Example
HTML
<div class="linkbox" id="linksbox">
<a id="Titr"> پیوند ها</a>
سایت روان آنلاین
</div>
jQuery
$('#Titr').click(function(e) {
e.preventDefault();
var par = $(this).parent();
par.animate({height:par.height()==30?'':30},700);
});
And if you want something more "dynamic":
$('.linkbox').on('click', 'a:first', function(e) {
e.preventDefault();
var par = $(this).parent();
par.animate({height:par.height()==30?'':30},700);
});
Keep in mind, last solution only works for jQuery versions 1.7 and above, for older version, replace .on with .delegate

You're sure that this condition document.getElementById(idd).style.height!=30 is satisfied?
I believe that the property height comes as string with the "px" sufix. See this.
So, to work it may be if (document.getElementById(idd).style.height!="30px").
BTW, is a best pratice to use only jQuery or pure Javascript, not mix them.

You could use jQuery for all of the function, instead of part of it:
function jamsho(id)
{
var $this = $(id);
alert($this.height());
if ($this.height() != 30)
{
$this.stop().animate({height:30},700);
divheight = $this.height();
}
else if ($this.height() == 30)
{
$this.animate({height:divheight},700);
}
}

I don't think you can apply jQuery animations to non-jQuery Objects
function jamsho(id) {
alert($(id).css("height");
if($(id).css("height")!=30)
{
$(id).stop().animate({height:30},700);
divheight=$(id).css("height");
}
else if ($(id).css("height")==30)
{
$(id).animate({height:divheight},700);
}
}

Try something like this:
var $div = $('#linksbox'),
divHeight = $div.height();
$('#Titr').click(function() {
if (!$div.hasClass('expanded')) {
$div.animate({height: 40}, 700, function() {
$(this).addClass('expanded');
});
}
else {
$div.animate({height: divHeight}, 700, function() {
$(this).removeClass('expanded');
});
}
});
http://jsfiddle.net/ZqEZ5/
A few notes:
no need to use document.getElementById with jQuery
don't use inline event handlers onClick.
Hope it helps.

Related

what is the best way to return the orginal style when mouseleave jquery?

I use mouseenter to input a new html. I face a challenge that I need to return the original style when mouse leave? When mouseleave, I need to remove the new html and use the original html What is the best way to do that?
var eye_disease1 = $('#eye_disease1');
eye_disease1.mouseenter(function () {
eye_disease1.html('<span class="show_li">symptoms</span><span class="show_li_2">diseases</span>').hide().fadeIn();
eye_disease1.css('border', 'none');
}).mouseleave(function () {
// what should I put here to return the original
});
Get the original HTML of eye_disease1 before changing and after mouse leave update HTML.
var eye_disease1 = $('#eye_disease1'),
diseaseHtml = '';
eye_disease1.mouseenter(function () {
if (!diseaseHtml) {
diseaseHtml = eye_disease1.html();
}
eye_disease1.html('<span class="show_li">symptoms</span><span class="show_li_2">diseases</span>').hide().fadeIn();
eye_disease1.css('border', 'none');
}).mouseleave(function () {
diseaseHtml = '';
eye_disease1.html(diseaseHtml);
});
You can all use the addClass
`$("selector").mouseenter(function(){
$(this).addClass("active");
})
$("selector").mouseleave(function(){
$(this).removeClass("active");
})`
var eye_disease1=$('#eye_disease1');
var eye_disease1_html;
eye_disease1.hover(
function() {
eye_disease_1_html = eye_disease1.html();
eye_disease1.html('<span class="show_li">symptoms</span><span class="show_li_2">diseases</span>')
.fadeOut(0)
.css('border','none')
.fadeIn(400);
}, function() {
eye_disease1.find('span.show_li, span.show_li_2')
.fadeOut(400)
.delay(400)
.html(eye_disease1_html)
.fadeIn(0);
}
);
But yeah I would prefer to have all the content inside (original, and the hovered content) there the whole time.
HTML:
<div id="eye_disease1">
<div class="original-content">
Original Content
</div>
<div class="hovered-content">
<span class="show_li">symptoms</span>
<span class="show_li_2">diseases</span>
</div>
</div>
CSS:
.hovered-content {
display: none;
}
.hovered {
border: none;
}
JS:
$('#eye_disease1').hover(
function() {
$(this).addClass("hovered");
$(this).find(".original-content").fadeOut();
$(this).find(".hovered-content").fadeIn();
}, function() {
$(this).removeClass("hovered");
$(this).find(".hovered-content").fadeOut();
$(this).find(".original-content").fadeIn();
}
);
You can see it here: https://jsfiddle.net/waga7Lu1/3/
The transition effect is a bit clumsy but I'm not really sure what you're after.

Jquery Scroll() requires 2 Arguments

I am trying to remove a class from a menu bar when the user scrolls down a page. I read the following topic and doc to get an idea on jquery scroll():
1) https://stackoverflow.com/a/16391580/1050957
2) http://api.jquery.com/scroll/
This is my code:
var jquery = jQuery.noConflict();
jquery(document).ready(function(){
$(window).scroll(function () {
if (document.body.scrollTop > 100)
$('#menuBar').removeClass( "nav-menu" );
else
// something something
});
});
The above code is an extract from the SO answer from another topic (link given above). But when I add that code, I am seeing: Not enough arguments to Window.scroll. error for $(window).scroll(function (). I dont know why its expecting 2 arguments since the doc I read on scroll() uses without an argument. Have I done something wrong? Or has something changed with the later version of Jquery?
I am using jquery v1.11.0
Use a full jquery code. Working example:
#menuBar { background: yellow; width: 50px; height: 800px; }
#menuBar.nav-menu { background: red; }
<div id="menuBar" class="nav-menu"></div>
<div style="margin-bottom: 999em;"></div>
$(document).ready(function(){
$(window).on('scroll', function () {
var $body = $('body');
var $target = $('#menuBar');
if ($body.scrollTop() > 100 && $target.hasClass('nav-menu')){
$target.removeClass("nav-menu");
}
else if( $body.scrollTop() <= 100 && !$target.hasClass('nav-menu') ){
$target.addClass('nav-menu');
}
});
});
Make sure to check if the class is already added to prevent innecesary stuff.
Check jsfiddle
You can add an empty param if needed to your scroll function:
$(document).ready(function(){
$(window).scroll([], function () {
...
});
});
Take a look at this:
http://colorlib.com/wp/forums/topic/fix-a-bug-in-latest-version-window-scroll/

jQuery css height not applying

For some reason the height is not being set in this piece of code
jQuery(document).ready(function() {
jQuery('#main-content').css({'height': ((jQuery(window).height()))+'px'})
jQuery('#nav-icons a').click(function(){
jQuery('#nav-icons a').removeClass("active-icon");
jQuery(this).addClass( "active-icon" );
var toLoad = jQuery(this).attr('href')+' #main-content';
var toLoadSlider = jQuery(this).attr('href')+' #homepage-slider';
jQuery('#main-content , #homepage-slider').fadeOut(1000, loadContent);
function loadContent() {
jQuery('#homepage-slider').empty().load(toLoadSlider)
jQuery('#main-content').empty().load(toLoad,'',showNewContent())
}
function showNewContent() {
jQuery('#main-content , #homepage-slider').css({'height': ((jQuery(window).height()))+'px'}).hide().fadeIn(2000).removeAttr('id class');
}
return false;
interestingly, the exact same line of code in the showNewContent() does set the height.
The only logical reason for this is that jQuery('#main-content') in your first line is not the actual jQuery object representation of the DOM element of your choice.
You will have to figure that out yourself as to why things turn out this way.
Assuming that you have
<div id="main-content">
... content
</div><!--main-content-->
This should do the trick :
var windowHeight = jQuery(window).height();
jQuery(document).ready(function ($) {
$('#main-content').css({
height: windowHeight
});
// other scripts
}); // ready
JSFIDDLE

Apply a loop in JS between X and XX

So I have been trying to think of how to explain this in a way that makes sense, but I will show you below, as it makes more sense.
I have this code that works fine but I want to shorten it down into a for each loop or something.
$('.holder1').on({
click: function(){
$('.box1').css({display: 'none'});
$('.text1').css({display: 'block'});
}
});
$('.holder2').on({
click: function(){
$('.box2').css({display: 'none'});
$('.text2').css({display: 'block'});
}
});
$('.holder3').on({
click: function(){
$('.box3').css({display: 'none'});
$('.text3').css({display: 'block'});
}
});
I have this going on up to 40+, and obviously this code is horrific.
You can refactor the HTML code to use a common class and data attributes. Something like this:
<div class="holder" data-box="box1" data-text="text1"></div>
<div class="holder" data-box="box2" data-text="text2"></div>
<div class="holder" data-box="box3" data-text="text3"></div>
Then you can have a single click handler for all classes:
$('.holder').on({
click: function(){
$('.' + $(this).data('box')).css({ display: 'none' });
$('.' + $(this).data('text')).css({ display: 'block' });
}
});
This avoids the needs for ugly loops to add multiple handlers and iterative id attributes, which always turns in to a maintenance nightmare.
To solve this problem it is possible to iterate over holder elements using jQuery Attribute Starts With selector (API docs):
$.each('[class^="holder"]', function(index, item) {
$(item).on('click', function() {
$('.box' + index).css({display: 'none'});
$('.text' + index).css({display: 'block'});
});
});
I would prefer using some common class, though, as Rory McCrossan pointed out in his answer.
for (var i = 0; i< 40; i++) {
$('.holder' + i ).on({
click: function(){
$('.box' + i).css({display: 'none'});
$('.text' + i).css({display: 'block'});
}
});
}
or just add a common class and use it.
try this:
use class .box and .text instead
var holder = $(".holder1");
for (var i = 2; i<= 40; i++) {
holder.add($(".holder"+i));
}
$(holder).on(
'click', function(){
$('.box').css({display: 'none'});
$('.text').css({display: 'block'});
}
});
Assuming holders and boxes sit in their respective containers, like
<div>
<div class="holder">a</div>
<div class="holder">b</div>
<div class="holder">c</div>
<div class="holder">d</div>
</div>
<div>
<div class="box">a</div>
<div class="box">b</div>
<div class="box">c</div>
<div class="box">d</div>
</div>
you can get rid of box/text numbers altogether:
$(".holder").click(function() {
var n = $(this).index();
$(".box").eq(n).show();
});
This way it will be much easier to add new elements or change their order.
Use:
$("*[class^='holder']").on({
click: function(){
var id = $(this).attr("class").replace("holder","");
$('.box'+id).css({display: 'none'});
$('.text'+id).css({display: 'block'});
}
});

Jquery hide div partially

I would like to adjust the width of the div using jquery on click event, and i can't seem to figure out what the exact syntax is.
below is an example of what i tried so far.
$(function() {
$("#square").on("click", function(){
if($(this).css("width", "50")){
$(this).animate({width:"500"}, 1000);
} else {
$(this).animate({width:"50"}, 1000);
}
});
});
http://jsfiddle.net/4GGP8/
Thanks in advance.
In your if statement try $(this).width() == 50 instead, since first of all css(); functions retrieves the unit as well and second of all you're not making a comparison in the if statement like that, if anything you should do $(this).css('width') == "50px" to retrieve the width and compare it.
For future reference you can always use parseInt(); to get rid of the unit added by css
so doing this is also valid
if(parseInt($(this).css('width')) == "50")
The code:
$(function() {
$("#square").on("click", function(){
if($(this).width() == 50){
$(this).animate({width:"500"}, 1000);
} else {
$(this).animate({width:"50"}, 1000);
}
});
});
Here is the resulting fiddle
Try this -
jsFiddle
$("#square").on("click", function(){
if($(this).css('width') == '50px'){
$(this).animate({width:"500"}, 1000);
} else {
$(this).animate({width:"50"}, 1000);
}
});

Categories

Resources