LinDan ChongWei LinDan ChongWei - 6 months ago 9
jQuery Question

jQuery setting height of iframe based on if else condition upon click event?

Hi guys I have an iframe that changes in height every time I click on my div with the class "top". The code starts with the deault height of 300 and when I click my div "top" the height drops to 0. However when I click on my div again the height won't go to 300 as I want it to.

JS, CSS and HTML files in order:



$(document).ready(function () {
$(".top").click(function(){
var height = $("#target").height();
if(height === 300 ){
$("#target").height(0).slideUp();
} else{
$("#target").height(300).slideDown();
}
});
});

.top {
height: 100px;
width: 300px;
background-color: green;
}
.cb {
position: fixed;
right: 0;
bottom: 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="cb">
<div class="top"></div>
<iframe id="target" src="http://www.disney.com" width="300" height="300" frameborder="0" scrolling="no"></iframe>
</div>





I'm new to jQuery So please advice me how I can implement a slide up and down function too on my iframe so when I click the div it will slide up and down nicely. Thanks and have a great day!

Answer
 if(height = 300)

should be

 if(height==300)

or better yet (check type in addition to value)

 if(height===300)

Since "height = 300" is an expression, it's assigning a variable named 'height' to 300. In a conditional statement, this returns true every time. Here is more information on conditional operators: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#Conditional_(ternary)_operator

Comments