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

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.

Related

pass variable to resize() jquery

I have two divs "#sidebar-wrapper" and ".j1". I am finding the height of ".j1" on window load, j1 changes size according to its content, now I have to apply this height to "#sidebar-wrapper".
I have tried this
var currentHeight = 0;
$(window).load(function() {
//get the natural page height -set it in variable above.
currentHeight = $('.j1').outerHeight();
console.log("set current height on load = " + currentHeight);
$("#sidebar-wrapper").resize(currentHeight);
});
I don't know what to use to set height of "#sidebar-wrapper".
Try to use next code example in order to get and set attributes cause may be your $("#sidebar-wrapper") is not exists yet(length 0 in jquery object):
document.addEventListener('DOMContentLoaded', function() {
currentHeight = $('.j1').outerHeight();
console.log("set current height on load = " + currentHeight);
$("#sidebar-wrapper").css('height',currentHeight );
console.log($("#sidebar-wrapper").height());
}, false);
Have you tried to change the CSS attribute height of #sidebar-wrapper?
JsFiddle
$("#sidebar-wrapper").css("height", currentHeight);
.resize method seems to be an event triggered when changing the size of your window. You can find more information about the resize event here: Resize Event.
$( window ).resize(function() {
$( "#log" ).append( "<div>Handler for .resize() called.</div>" );
});

Make two elements have the same size

I want two elements in different locations and different "parents" in the DOM tree to have the same height and width, even if one changes.
Is there a solution that will support all browsers including IE 8?
EDIT: If there is a solution that will not work on IE 8 I would still like to hear about it, but it will not be accepted as the solution I'm looking for.
Clarification: I want to solution to handle any cause for the size change: Window size change, content size change, etc.
You can use setInterval to do what you want.
var changeIndex = -1; // record element width or height is change or not
function setToSame() {
if(changeIndex!=-1) {
console.log("test");
$('.same').height($('.same').eq(changeIndex).height());
$('.same').width($('.same').eq(changeIndex).width());
changeIndex = -1;
}
}
// set your own function to change size, but reserve changeIndex setting
$('input').change(function() {
$(this).parent().children('.same').css($(this).attr('id'), $(this).val() +'px');
// set the changeIndex to the current change div
changeIndex = $('.same').index($(this).parent().children('.same'));
console.log(changeIndex);
});
setInterval(setToSame, 4);
See jsfiddle here.
You can use jQuery to get a solution that works for IE8.
Suppose the two element that you want to have same height and width are,
<div id="fir">
</div>
<div id="sec">
</div>
Now specify height and width of just one element as,
#fir{
height: 50px;
width: 100px;
}
There is no predefined method in CSS to detect height or width change but you can achieve the results using jQuery as,
$(document).ready(function(){
$('#fir').bind('heightChange', function(){
var h = $("#fir").height();
$("#sec").height(h);
});
$('#fir').bind('widthChange', function(){
var w = $("#fir").width();
$("#sec").width(w);
});
$('#sec').bind('heightChange', function(){
var h = $("#sec").height();
$("#fir").height(h);
});
$('#sec').bind('widthChange', function(){
var w = $("#sec").width();
$("#fir").width(w);
});
});
This will detect the height and width change for both element and set the height and width of other element likewise.
To check if the above code works properly you can create a test script that changes width of element with id="fir" by creating a button,
<button id="btn">Change width</button>
Now include the below function,
$("#btn").click(function() {
$("#fir").css('width', '400px');
$("#fir").trigger('widthChange');
});
Here is the fiddle for it
<html>
<head>
<style>
div{}
#A{background: red}
#B{background: blue}
</style>
<script>
mBlockChange = false; //Required for IE9-
function equalSize(f, t){
mBlockChange = true;
f = (f || document.getElementById('A'));
t = (t || document.getElementById('B'));
//We take the larger dimension of both since it is better than clipping.
//Change on your demands.
t.style.height = '';
t.style.width = '';
f.style.height = '';
f.style.width = '';
t.style.height = Math.max(f.offsetHeight, t.offsetHeight).toString() + 'px';
t.style.width = Math.max(f.offsetWidth, t.offsetWidth).toString() + 'px';
f.style.height = Math.max(f.offsetHeight, t.offsetHeight).toString() + 'px';
f.style.width = Math.max(f.offsetWidth, t.offsetWidth).toString() + 'px';
setTimeout(function(){mBlockChange = false}, 100);
}
//This one for IE9+, FFox, Chrome and Safari
//http://help.dottoro.com/ljrmcldi.php
function bindEvents(){
var tA = document.getElementById('A');
var tB = document.getElementById('B');
//The addEventListener() method is not supported in Internet Explorer 8 and earlier versions with resize.
//Resizing the body
document.body.onresize = function(){
//We only do this once the resizing is actually finished.
if (this.Timer) clearTimeout(this.Timer);
this.Timer = setTimeout(function(){
//console.log('Resize', this);
equalSize()
}, 300)
};
//If supported, we listen on dom changes.
if ('MutationEvent' in window){
document.addEventListener('DOMSubtreeModified', function(){
if (document.Timer) clearInterval(document.Timer);
//console.log('DOMSubtreeModified', this);
if (!mBlockChange) equalSize()
}, false);
}
//We set an interval for browsers which do not support DOMSubtreeModified
//If you do not want to rely on ('MutationEvent' in window) put it out of else and cancel the timer (scenario B)
//Can not bind parameters to setInterval in IE8- :s
else{
document.Timer = setInterval(function(){
//console.log('Interval', 'Document');
equalSize()
}, 1000);
}
}
</script>
</head>
<body onload = 'bindEvents()'>
<div id = 'A'><p contenteditable = 'true'>A</p></div>
<div id = 'B'><p contenteditable = 'true'>B</p></div>
</body>
</html>
https://jsfiddle.net/5cn7maqe/
Yet your elements height and width should not magically change, it always requires some interactions, like changing dom by ajax, oninput with contenteditable or resizing the window. You would be better off to just adjust it after those actions manually.
Edit: Made some minor changes.
https://jsfiddle.net/5cn7maqe/1/

Jquery .height() not working until resize of window

I'm using this code to resize a div on my page:
function sizeContent() {
var newHeight = ($("html").height() - $(".header").height() -3) + "px";
$(".content").height(newHeight);
}
I am triggering this using:
$(window).resize(sizeContent());
But I also call it inside
$(document).ready(sizeContent());
to set all the heights properly.
If i resize the browser window by dragging at its borders it works great.
But the initial call does not seem to have any effect. Putting an alert inside the sizeContent function I can see that it is being called at page ready, and is setting the right height, but nothing is changed on the page.
It's as if the browser does not recognize that it needs to redraw anything unless the window itself is changed.
Solved:
In the end it was not the javascript that was the problem, using div's with display:table and display:table-row was causing it. Removed these from the css and everything worked.
// If you put your code at the bottom of the page to avoid needing`$(document).ready`, it gets even simpler:
$(window).on('resize', function () {
var newheight = ($(window).height() - $('.header').height() - 3);
$(".content").css("height", newheight);
}).trigger('resize');
// Another way to do that same thing
$(document).ready(sizeContent);
$(window).on('resize', sizeContent);
function sizeContent() {
var newheight = ($(window).height() - $('.header').height() - 3);
$(".content").css("height", newheight);
}
// Another technique is to`.trigger()`one event inside the other:
$(window).on('resize', function () {
var newheight = ($(window).height() - $('.header').height() - 3);
$(".content").css("height", newheight);
});
$(document).ready(function () {
$(window).trigger('resize');
});
Replace
$(".content").css({height:newHeight}) //replace this
with
(".content").height(newHeight);
Use below code:
function sizeContent() {
var newHeight = ($(window).height() - $(".header").css('height')-3) ;
$(".content").css('height',newHeight);
}

jQuery Click event works only once (none of the previous Stack Overflow answers helped)

What I'm trying to do is that when the page loads I'm resetting an image to my desired small size.
If the user clicks on the image later it should enlarge with an animation, I'm done up to this part.
When the user again clicks on that image it should be resized to the size that I assigned after loading the page, I have tried toggle event, but that's not working, toggle just makes my images disappear from the page. So I created an alternate to toggle event by using if and else condition and a flag variable called "small" but the problem is that click event is working only once i.e: If the image is in the small size and I click on it, the image gets enlarged but when I click on it again the click event is fired but it doesn't work, I wish if there is any way that I could make it work with toggle event, otherwise I would like to do it by using if and else condition in click event.
Here's the HTML:
<html>
<head>
<title></title>
<script src="jquery-1.10.1.min.js"></script>
<script src="index.js"></script>
</head>
<body>
<img src="wordpress.jpg" class="small-Img" id="test"> <br>
<img src="store.jpg" class="small-Img">
</body>
</html>
Here's the script:
$(document).ready(function() {
var small;
$('.small-Img').on('load',function(){
$(".small-Img").attr('width','200');
small=Number(1);
});
$('.small-Img').on('click',function () {
alert("event fired");
if(small==1){
var obj=$(this);
var originalWidth=obj[0].naturalWidth;
var originalHeight=obj[0].naturalHeight;
$(this).animate({ height: originalHeight, width: originalWidth }, 1000, function() { });
small=Number(0);
}
if(small==0){
$(".small-Img").attr('width','200');
small=Number(1);
}
});
});
Your code
$(".small-Img").attr('width','200');
sets a width attribute on the image, similar to <img src="url" width="200"> which probably doesn't result in a size change. Try
$('.small-Img').css('width','200px');
or animate the shrinking
$('.small-Img').animate({ width: '200px' }, 1000);
You may also get better results making small an attribute of your image rather than a property of the window object
jsfiddle
It sounds like the problem isn't that the event isn't fired multiple times, but that it doesn't enter your if statement. Try making small a boolean variable instead of a number, that way you can avoid all the == vs === messyness
EDIT:
Also, you probably want an else if so that it doesn't shrink once it enlarges on each click.
DEMO
for setting or getting css value we use .css() not .attr()
== only checks the value
=== checks the value and the datatype
$(document).ready(function () {
var small;
$('.small-Img').on('load', function () {
$(".small-Img").css('width', '200'); //changed attr to css
small = 1;
});
$('.small-Img').on('click', function () {
if (small === 1) { //changed == to ===
var obj = $(this);
var originalWidth = obj[0].naturalWidth;
var originalHeight = obj[0].naturalHeight;
$(this).animate({
height: originalHeight,
width: originalWidth
}, 1000, function () {});
small = 0;
}
if (small === 0) { //changed == to ===
$(".small-Img").css('width', '200'); //changed attr to css
small = 1;
}
});
});
How about first making "small" a data-attribute on the image itself? Not a big deal, but a little more convenient (IMHO). The next thing is, when you want to check the second click, you might consider doing an else if rather than just an if. Not sure if it makes a difference, but it is a clear logical differentiation, you can have one or the other -- not both. Third, if you animate the width back down, you might also animate the height, calculated by your small height divided by your original height times the original width. Seems to work, see it here: http://jsfiddle.net/snowMonkey/7nCMF/1/
$('.small-Img').css('width','200px').data("small", 1);
$('.small-Img').on('click',function () {
var that=this;
this.smallWidth = "200px";
this.smallHeight = (200/$(this)[0].naturalWidth) * $(this)[0].naturalHeight+"px";
if($(this).data("small")===1 ){
var obj=$(that);
var originalWidth=obj[0].naturalWidth;
var originalHeight=obj[0].naturalHeight;
$(that).animate({
height: originalHeight,
width: originalWidth
}, 1000, function() { });
$(that).data("small",0);
} else if($(this).data("small")===0){
$(that).animate({
width: that.smallWidth,
height: that.smallHeight
}, 1000, function(){}).data("small", 1);
}
});
Best of luck!

Javascript - how to call function correctly

I don't really understand how to call a Javascript function properly on document ready. My goal is to resize a div depending on the height of browser window, and I took this code from another answer on SO. What am I doing wrong?
function resizeElementHeight(element) {
var height = 0;
var body = window.document.body;
if (window.innerHeight) {
height = window.innerHeight;
} else if (body.parentElement.clientHeight) {
height = body.parentElement.clientHeight;
} else if (body && body.clientHeight) {
height = body.clientHeight;
}
element.style.height = ((height - element.offsetTop) + "px");
}
$(document).ready(resizeElementHeight($('#global_image')));
The element I am trying to call has the id "global_image", but I get "cannot set property height of undefined", and I feel lost in how to providing the right element to the function. Thanks for your help!
ready() expects a function as its argument. Right now, you are calling resizeElementHeight() and passing its return value to ready().
In your current code, at the point of calling resizeElementHeight() the DOM is not yet ready and the element #global_image is not yet in the DOM tree.
You should change it to:
$(document).ready(function() {
resizeElementHeight($('#global_image'));
});
The function resizeElementHeight expects a DOM-element, not a JavaScript object. To expand on techfoobar's answer you should change it to:
$(document).ready(function() {
resizeElementHeight($('#global_image')[0]);
});
the DOM object is not completely loaded when you call resizeElementHeight.replace by is:
$(document).ready(function() {
resizeElementHeight($('#global_image')[0]);
});

Categories

Resources