javascript setting height - javascript

I am trying to do very simple thing, setting the height of div depends on what the height is.
So when the site load the height is 45px, after clicking in button height is 100px. After the next click I want my height back to 45px. I am using jQuery, the code is below:
http://codepen.io/zlyfenek/pen/pAcaw
Thanks for any help, as I am new to jQuery.

You can use .toggleClass() function of jQuery.
$(function(){
$('.yourButton').click(function(){
$('.yourDiv').toggleClass('big');
});
});
demo: http://jsfiddle.net/FYyU6/
Note:
Your big css class should come after your small class Order Matters.

change $("button").one to $("button").on

You should just have a class that sets the height to 100px, and then toggle it when you click on the button:
.opened { height: 100px; }
$("button").on("click", function() {
$(".con_b").toggleClass("opened");
})

function showHeight(ele, h) {
$("div").text("The height for the " + ele +
" is " + h + "px.");
}
// use .on instead of .one, .one will online listen for a click one time,
// so your second click will not be seen
$("button").on('click', function () {
if ($(".con_b").height() == 45)
{
$(".con_b").height(100);
}
else
{
// show height and change height should be two different actions
$('.con_b').height(45);
showHeight(".con_b",$(".con_b").height());
}
});

function showHeight(ele, h) {
$("div").text("The height for the " + ele +
" is " + h + "px.");
}
$("button").on('click', function () {
if ($(".con_b").height() == 45)
{
$(".con_b").height(100);
}
else
{
$(".con_b").height(45);
}
its $("button").on not $("button").one

Related

How do I operate with the width on a jQuery click event?

I am creating a function that each time it is called 1px is subtracted to the width of an image. I can't figure it out...
Something like this:
var leafCompress = function(){
.css("width" -1 + "px"); //This line is definitely wrong
}
(The following code is working) Here I'm adding the event listener so on each click it calls the leafCompress function.
leaf.on("click",function(){
leafCompress();
});
the problem comes from your function leafCompress
$( "#panda" ).on('click', () => {
resize();
});
const resize = () => {
let width = $("#panda").width() - 50; // get the width of the image and substract 50
$("#panda").css("width", width);
}
#panda {
width: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="panda" src="http://r.ddmcdn.com/w_624/s_f/o_1/cx_0/cy_17/cw_624/ch_416/APL/uploads/2014/06/red-panda-09-625x350.jpg" />
I am not sure if you are using jQuery but, you can do it with jQuery .width function,
the css('width') function returns the width as string i.e: "780px" and to use it to set the width property you usually do .css('width', valueToBeSet)
However you can achieve the same result using jQuery .width function
$().width() will return the actual width and $().width(value) will set width as the value
The most trivial way:
leaf.click(function(){
var node = $(this);
node.css('width', node.width() - 1 + 'px');
})
If event handler is a function, "this" points to event target.

How to add a javascript transition to jquery expanding text?

I've got a problem with creating a transition for a collapsing text-jquery plugin I've found. Unfortunatley I've go almost no understanding to javascript. At the bottom I added "&&(this).show('fast');" but it didn't work. Hopefully you can help.
$(document).ready(function () {
var maxheight=16;
var showText="Weiterlesen";
var hideText="Zusammenklappen";
$('.expand').each(function () {
var text = $(this);
if (text.height() > maxheight){
text.css({ 'overflow':'hidden','height': maxheight + 'px' });
var link = $('<p class="weiter" id="noselect"><a>' + showText + '</a></p>');
var linkDiv = $('<div></div>');
linkDiv.append(link);
$(this).after(linkDiv);
link.click(function (event) {
event.preventDefault();
if (text.height() > maxheight) {
$(this).html('<a>' + showText + '</p>');
text.css('height', maxheight + 'px')
&&(this).show('fast');
} else {
$(this).html('<a>' + hideText + '</p>');
text.css('height', 'auto')
&&(this).show('fast');
}
});
}
});
});
Try Changing it to this
$(this).html('<a>' + hideText + '</p>');
text.css('height', 'auto');
$(this).show('fast');
This is using the correct JQuery syntax, wether it works or not depends on what "this" is.
(this).show();
wont work. this is an HTML Element , and it has no show property. You want the jquerys object property.
jQuery(this)//get the jquery object of that html el
.show();//call the function on that
$ is just a shortform of jQuery. So:
$(this).show();
Note this is the link, but you want to show the text (wich is already a jquery object):
text.show();
Concerning the && ( the AND operator):
false && alert("nope");
true && alert("yes");
a() && b(); //b is just called if a() is truthy => can create bugs in your case
Ita not neccessary / useful to use this operator here. However, you could use the Comma operator, but its common to simply use two statements...
However, if ive got you right, its not neccessary to show but rather to add a transition. That can be done with css:
.expand{
transition:all 2s ease;
}
Note this doesnt work for height, but for max-height, so one may set height:auto and change max height from 0px to 500%...

Animate background image javascript not working

I want to achieve a background animate image, that moves from right to left, but the image won´t animate, could you help me verify my code?
<body>
<div id="background-container"></div>
<script> type="text/javascipt">
function animateBackground(elem, speed) {
var x = 0 ;
var y = -50;
elem.style.backgroundPosition = x + 'px' + ' ' + y + 'px';
var timer = setInterval (function(speed) {
elem.style.backgroundPosition = x + 'px' + ' ' + y + 'px';
x--;
if (x == -600) {
clearInterval(timer);
}
},speed)
}
document.addEventListener("DOMContentLoaded", animateBackground(document.getElementById('background-container'), 15), false);
</script>
</body>
Your code is quite ugly but actually it looks fine. What is definitely wrong is how you are adding the event handler. Instead of adding a handler function, you call your handler function inline, so it actually doesn't add any listener. You should pass the function itself, for example like this, using an anonymous function inline.
document.addEventListener("DOMContentLoaded", function() { animateBackground(document.getElementById('background-container'), 15); }, false);
You could have provided a jsfiddle link, which would have made it easy. By the way here is the working jsfiddle, https://jsfiddle.net/pmankar/4o88z0tt/
I added a css background to the div tag using
div{
background-image: url("https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png");
height: 100px;
width: 600px;
border: 2px solid green;
}
Rest assured, I didn't do any changes to your js code or the html code. It worked fine for me.

Resizing font based on html length

I know there are a lot of similar posts, but I have not thus far been able to solve this.
context:
User selects a home,
homes have unique titles,
depending on title, resize font to prevent overflow
JS Fiddle: https://jsfiddle.net/9uvpun5o/3/
$(function() {
var that = $('#title'),
planName = that.html().length
;
// depending on html length, update font-size
if(planName > 30) {
that.css('font-size', '10px');
} else if(planName > 20) {
that.css('font-size', '12px');
} else if(planName > 10) {
that.css('font-size', '15px');
}
});
Font is sized according to html length, but I need this to be reactive. I tried creating an .on("change") event, but failed to implement correctly. Help?
Right now I'm just updating the title from console,
$('#title').html("big long description thing");
But, this will be done by selecting from a modal menu in the future.
EDIT
Ok, now I got it. Your JS should be this then:
$(function() {
$('#title').on('DOMSubtreeModified', function() {
var title = $('#title'),
planName = title.html().length;
// depending on html length, update font-size
if(planName > 30) {
title.css('font-size', '10px');
} else if(planName > 20) {
title.css('font-size', '12px');
} else if(planName > 10) {
title.css('font-size', '15px');
}
});
$('li').on('click', function() {
$('#title').text( $(this).text() );
});
});
The DOMSubtreeModified should fire whenever the content of the element changes (as this modifies the DOM Subtree). The 'click' part is not necessary, but I've kept it for testing purposes.
According to Dottoro, Opera doesn't support this event and IE 9 and below may not support or be buggy.
For more options and informations, check these other StackOverflow question:
The question from where I got this solution
Suggestion with Mutation Events API
By what you said, an user will "select a unit":
use case:
User selects a unit,
units have unique titles,
depending on title, resize font to prevent overflow
So, you need to change the font-size as part of this action. I used your code to make an example:
HTML
<ul>
<li>On load, font size is set depending on length of title.</li>
<li>However, I want this to be reactive...</li>
<li>Change the length of Title and hit run</li>
<li>Try clicking these itens</li>
<li>You will see</li>
<ul>
<br/><br/>
<span id="title">TEST TEST</span><br/>
JS
$(function() {
$('li').on('click', function() {
var titleEl = $('#title').text( $(this).text() ),
planName = titleEl.text().length;
// depending on text length, update font-size
if (planName > 30) {
titleEl.css('font-size', '10px');
} else if (planName > 20) {
titleEl.css('font-size', '12px');
} else if(planName > 10) {
titleEl.css ('font-size', '15px');
}
});
});
Try to click in the list itens. You see? As a response to "changing the unit", the title and font-size changes.
If this answer doesn't help you, give more details.
I might do this with a combination of a bit of CSS to prevent the text from wrapping, then I would use some script to measure the length of the rendered text. If it's longer than whatever your predetermined maximum width is, use the script to apply a CSS transform.
#title {
white-space: nowrap;
display: inline-block; /* necessary for the scale to actually work */
transform-origin: 0% 100%; /* set transform origin to bottom left corner of the title element */
}
.maxwidth-container {
width: 400px;
}
Then in your script:
var scaleTitle = function() {
var $title = $("#title");
var maxWidth = $(".maxwidth-container").width();
$title.css("transform","scale(1,1)"); //reset to normal scale in order to measure natural width
if ($title.width() > maxWidth) {
var scaleAmt = maxWidth / $title.width();
$title.css("transform" , "scale(" + scaleAmt + "," + scaleAmt + ")");
}
};
In your case, I have wrapped your #title element in a container that dictates the maximum size, but you could use an explicit set amount.
Call this function every time the user selects a home.
Example here:
https://jsfiddle.net/9uvpun5o/5/
This will work.TRy this
var planName = $("#title").text().length;
if(planName > 30) {
$('#title').css("fontSize", "16px");
}else{ if(planName > 20) {
$("#title").css("fontSize", "12px");
}else if(planName > 8) {
$("#title").css("fontSize","24px")
}

Resizing function appends elements multiple times

I have a bit of code that needs to detect scrollbars on resize and load. This is straightforward enough, the issue arises when I run the append() function, it appends the elements over and over again.
Below is the jQuery I am using (the demo is here)
$.fn.hasScrollBar = function() {
return this.get(0).scrollWidth > this.width();
}
$(window).on("resize", function () {
var tableWidth = $("table").width();
var wrapper = "<div class='top-scroll'><div class='inner'></div></div>";
var instruction = "<span class='instructions'>Scroll left to see more information</span>";
// This sets the overflow message and a placeholder width to match the table
if( $('.no-overflow').hasScrollBar()){
$('.no-overflow').before(wrapper);
$('.top-scroll').before(instruction);
$('.top-scroll').children().attr("style", "width:" + tableWidth + "px;");
}
// This synchronises the scrollbars
$(".top-scroll").scroll(function(){
$(".no-overflow")
.scrollLeft($(".top-scroll").scrollLeft());
});
$(".no-overflow").scroll(function(){
$(".top-scroll")
.scrollLeft($(".no-overflow").scrollLeft());
});
}).resize();
I'd like the append to only happen once and also remove when there are no scrollbars present.
To check for scrollbars:
if ($(document).height() > $(window).height()) {
//There is a vertical scrollbar
} else {
//There is no vertical scrollbar
}
To only create one .top-scroll:
if( $('.no-overflow').hasScrollBar() && $('.top-scroll').length < 1) { // Check .top-scroll doesn't exists currently
$('.no-overflow').before(wrapper);
$('.top-scroll').before(instruction);
$('.top-scroll').children().attr("style", "width:" + tableWidth + "px;");
}
I would also put your 3 variable declarations within your if statement so they will only be set if the statement is true. Unless of course you are using them elsewhere.

Categories

Resources