Resizing multiple images via jquery one at a time - javascript

So I am writing some jquery that is basically meant to resize any image when I click on it, meaning I can click on one image and resize it, and then click on any other image and start resizing it as well, but idependently. The code I have to do this is as follows:
$('img').click(function(e) {
thisImage = this;
$(document).keypress(function(event) {
if ( event.which == 115) {
$(thisImage).css('width', "+=25").css('height', "+=25");
};
if ( event.which == 97) {
$(thisImage).css('width', "-=25").css('height', "-=25");
};
});
});
This works fine the first time you use it. You can click on an image when there is more than one image present and the image that you clicked on will resize appropriately when you hit the appropriate buttons. Upon clicking the second image to resize it, however, both it and the first image you clicked will start resizing together. This scales with as many images as you can put on the page, i.e., three images will resize together after each has been clicked on.
Does anyone know why this is happening and how I can stop it? I would like to be able to click each image and be able to resize it independently, no matter the order it was clicked on. I have a feeling this has something to do with the way I am using "this," but I am relatively new to jquery and javascript so I cannot think what it would be.
Any help would be appreciated. Thanks!
-Alex

Essentially the issue here is that each time you click an image, you are binding a new listener to the document.
This means that every time you press a key, you invoke all of the listeners that you have added. What you would want to do is unbind the listeners that are still on the document when you click the next image, which will mean that only one image will be listening for your keypresses at a time.
For example, in this jsfiddle we have the code:
$('#in').keypress(function(event) { alert('first'+event.which); });
//$('input').unbind('keypress');
$('#in').keypress(function(event) { alert('second'+event.which); });
Which adds two listeners to an input element, and as you can see by pressing a key within the element, it causes both listeners to run. Essentially you are adding a new keypress listener each time you click an image, and the old ones are never being cleared out. If you uncomment the unbinding command in the jsfiddle, you will see that only the second alert will be invoked, because the first listener is released. If you only ever want the keys to be listening to one image at a time, then you will want to have something along the lines of $(document).unbind('keypress') at the beginning of the click listener (of course this will clear all keypresses, so if you have other listeners attached to the document you will want to be a bit more careful managing them, for this problem it will be sufficient).

Yes, that's how it will work with this code.
Reason is, in the img.click event handler you attach a new event handler on document.keypress which will resize the image by passing it a reference to 'thisImage'.
What happens is, this document.keypress event handler for this image will continue to live on, even if you click on another image, and will resize the image on each keypress.
These event handlers will continue to accumelate as you keep selecting new images.
What you need to do is remove the previous event handlers when user clicks on a new image.

Related

Is it possible to detect a mouse click on a page on every element?

I want to trigger a function if a user clicks anywhere on the page, even clicking on no element or link. Is it possible?
The extension runs only on youtube.com so I can't add every element on the page to the trigger and I assume that every page has different element's ids.
Emmanouil Chountasis is correct, you can use the code at "Detect left mouse button press" to detect a left mouse click crossbrowser.
To the heart of your question, I think what you're looking for is Event Delegation. In jQuery,
// Select a wrapper for the events
$('body')
// Whenever any element in the <body> is clicked
.on('click', '*', function (evt) {
// Emmanouil Chountasis's suggestion would be called right here
if (isLeftClick(evt)) {
// ... do stuff
}
});
See http://learn.jquery.com/events/event-delegation/
Reed's answer works fine, but it triggers the action multiple times. I found this solution that only works on left mouse triggers and executes once per click.
$("body").unbind().click(function() {
//Do Stuff
});

Check pressed mouse button when page is loading

I need to check in my javascript code which mouse buttons are pressed. It's not so hard to do but I need to check it when a page is just loading and no mousedown event was fired in that page yet. For example when onload event is fired. Is it possible? It can be done with jQuery too if it wouldn't be done only with javascript.
JavaScript does not provide mouse button state query outside of event handlers.
But in principle you can check if body is in :active state thus has mouse pressed on it.
console.log($(document.body).is(":active"));
I believe if you need to get clicks before the page finishes loading (and after) you could do it using load instead of ready.
$(document).load(onLoad);
function(onLoad){
$('body').mousedown(function(event){
var mouseClick = [];
mouseClick.push(event.which);
});
}
or whatever mouse click tracking code you need.

Synchronising browser events in JS

This is a bit of an abstract question, but I've been pondering its usefulness, and maybe it's either already been solved or inspires someone to do something based on it.
Well recently I ran across an issue whereby three browser events were fired, all as the result of a single user interaction: click, blur and focus. When the user clicks from one input to another, these events occur; and a similar set occur when the user tabs from one to another.
The trouble I had was that they fired in this order: blur, focus, click. It meant that, if the blur event caused DOM changes, the click event could be affected. I really wanted click, blur, focus - but that's not what the browser gave me.
I figured a general utility could be produced, capturing and cancelling browser events, then synchronising them and firing a single handler for all three. Perhaps extending the Event class so that the event could be reinstated.
Is there a more abstract design pattern I can use here? Something that will allow me to set up an arbitrary number of event listeners, and then fire a single event when all are complete? Does it have an implementation already? All advice welcome.
Dont need to break head around this! you can always trigger these events Programmatically
Note: object referenced here is any element selected using javascript selector.
Initially onBlur & onFocus do event.preventDefault which allows onClick to do its job first
var clicked=false;
object.onblur = function(e) {
if (!clicked) {
e.preventDefault
}
};
object.onfocus = function(e) {
if (!clicked) {
e.preventDefault
}
};
inside click event undo the above preventions and trigger the events in the order you wanted
object.onclick=function(){
clicked=true;
//Do anything
object.unbind('blur'); //this do undo prevent default
object.unbind('focus'); //this do undo prevent default
object.blur(); //in order you want
object.focus();
//make sure to put condition if click clicked
};
Thats it ! Hope it helps

contenteditable: trigger event on image resize when using handles

Just in firefox i want to trigger an event whenever the size of an image is changed.
When you click an image in a contenteditable area firefox gives it handles and you can adjust the size, as soon as the mouseup is done i want to trigger an event so i can get some information from the image, the rest is easy, i just cant find something that fires off when the handle is dragged and let go on the image.
Im guessing something in jquery could monitor the div using the live function.
You may observe the DOMAttrModified-event:
editableDivNode
.addEventListener ('DOMAttrModified',
function(e)
{
if(e.target.tagName=='IMG'
&& e.target.getAttribute('_moz_resizing')
&& e.attrName=='style'
&& e.newValue.match(/width|height/))
{
//do something here but don't prompt the user
}
},
false);

Javascript/jQuery: mouseenter event not firing properly

I have a code like this
$('#singleColumn' + time).show(SHOW_COMPONENT_SPEED)
.live('mouseenter', function() { $('#propertiesButtonSingle' + time).fadeIn(FADEIN_SPEED); })
.live('mouseleave', function() { $('#propertiesButtonSingle' + time).fadeOut(FADEOUT_SPEED); });
which I'm using to show/hide a button when mouseenter/mouseleave events are fired on a box.
The problem is that my page is dynamic, i.e. I keep adding new HTML to the page using JQuery .html() function. What happes is that the mouse events are fired only for the last box I added (I add them by drag and dropping): pratically it works fine for the first box, if I add a second one the events are fired correctly for it but when I move the mouse over the first box nothing happens. If I add a third box the second one stops working too, etc...
The code I posted is for one kind of box, but for the other types it is pratically the same apart from the selector names.
take a look at .delegate() - http://api.jquery.com/delegate
you could bind events to an object higher up the DOM tree and listen ...

Categories