Shorthand to get jquery object from event? - javascript

Is there a way to get a jquery object back from an event to reduce the amount of $(e.target) that has to be done?
For example:
$(document).on('click',"div", function(e){
$(e.target).css('color', 'red');
}
});
could be written as
$(document).on('click',"div", function(e){
e.JQUERY_target.css('color', 'red');
}
});
Is there a way to get a jquery object from the event without having to convert it?

Is there a way to get a jquery object back from an event to reduce the
amount of $(e.target) that has to be done?
Yes. Do not use jQuery for the task. jQuery is not necessary at all for the specific requirement
$(document).on("click", "div", function(e){
e.target.style.color = "red";
});

No, events give you only DOM objects. If you want to use jQuery, $() them.

You can harness the awesome power of this!
$(document).on('click', 'div', function(){
$(this).css('color', 'red');
});
Where $(this) is the current object you are running code on. In this case, you're saying that whenever a div that is a child of document is clicked on, you want to run the given code on it. Thus, this is the div that was clicked on.

You can use $(this) if you want to use jQuery methods. Or e.target if you want to use vanilla JS methods.
Using $(this) with jQuery methods:
$(document).on('click', "div", function(e) {
$(this).css('color', 'red');
});
div {
width: 100px;
height: 100px;
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Click Me</div>
Using e.target with vanilla JS methods:
$(document).on('click', "div", function(e) {
e.target.style.color = 'red';
});
div {
width: 100px;
height: 100px;
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Click Me</div>

Related

How can i add a event function after append a elements?

I click the button, it will append a div inside body, then, I want to click the div to alert a msg.I tried, but fail. How can I implements with highlight area.
example
$(document).ready(function()
{
$("button").click(function()
{
div = "<div class='test'>div</div>";
$("body").append(div);
});
$(".test").click(function()
{
alert("test");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Append div</button>
You should note that when document is ready elements with the .test class do not exist (that is why your code didn't work), they are dinamically added. So, I will do like this:
$(document).ready(function()
{
$("button").click(function()
{
var div = $("<div></div>").addClass('test'); // this is creating div element in dom as jquery
// Then attach click function to purpose of its create
div.click(function()
{
alert('test')
});
$("body").append(div);// then this is appending created div
});
});
jsfiddle Playground
One way, is just registering the listener on click event after you append it to the body tag, taking care of unregistering the previous clicks events, so you don't fall on multiple clicks events on the same element. Note that when document is ready still don't exists any element with the class .test, thats the reason your code was not working. Check next example:
$(document).ready(function()
{
$("button").click(function()
{
var div = "<div class='test'></div>";
$("body").append(div);
$(".test").unbind("click").click(function()
{
alert("A new div was clicked!");
});
});
});
.test {
width: 200px;
height: 200px;
background: red;
margin-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button type="button">Append new div</button>
</body>
For dynamically created elements, use .on, lear more about .on here http://api.jquery.com/on/
$(document).ready(function(){
$("button").click(function(){
div = "<div class='test'></div>";
$("body").append(div);
});
$(document).on('click', '.test', function(){
alert("test");
});
});

remove the element that's leaved

I have mouseleave event. When I leave the element, I wan't to remove that element that I mouseleaved from (if this give sense). Example below, and what I tried. I supposed that I can't do it that way because that's not how it works (I guess), but what is the propper way to do it? Atm. I can't use a selector like:
$('#wrapper').remove()
rather than
$(document).on('mouseleave', '#wrapper', function(e) {
console.log($(this).remove());
alert('Mouse leaved and wrapper should be removed');
});
$(document).on('mouseleave', '#wrapper', function(e) {
console.log($(this).remove);
alert('Mouse leaved and wrapper should be removed');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">asdcasdcasd</div>
remove() is a method not property. Use remove() not remove
$(document).on('mouseleave', '#wrapper', function(e) {
console.log($(this).remove());
alert('Mouse leaved and wrapper should be removed');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">asdcasdcasd</div>

Why document selector doesn't work for mouseenter event?

Here is my code:
$.fn.right = function() {
return $(document).width() - (this.offset().left + this.outerWidth());
}
$(document).ready(function(){
$('a').bind('mouseenter', function() {
var self = $(this);
this.iid = setTimeout(function() {
var tag_name = self.text(),
top = self.position().top + self.outerHeight(true),
right = self.right();
$('body').append("<div class='tag_info'>Some explanations about "+tag_name+"</div>");
$(".tag_info").css({top: top + "px", right: right + "px"}).fadeIn(200);
}, 525);
}).bind('mouseleave', function(){
if(this.iid){
clearTimeout(this.iid)
$('.tag_info').remove();
}
});
});
body{
padding: 20px;
direction: rtl;
}
a {
color: #3e6d8e !important;
background-color: #E1ECF4;
padding: 2px 5px;
}
.tag_info{
position: absolute;
width: 130px;
height: 100px;
display:none;
background-color: black;
color: white;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a>long-length-tag</a>
<a>tag</a>
It works fine. But in reality, the content (those tags) will be created later. I mean they will be created as an ajax response. So $('a') doesn't select them.
Now I'v written it like $(document).bind('mouseenter', 'a', function(){ ... }) to make that working even for the DOM which is created after page loading.
But as you see in this fiddle, it doesn't work. Does anybody know what's the problem and how can I fix it?
You need to bind the event with .on(). This works for future elements as well.
$(document).on('mouseenter', 'a', function(){ ... });
And, as #Gregg has answered, .bind() has been replaced by .on(). That's the actual cause why your fiddle doesn't work.
The on() function has replaced bind() since jQuery 1.7. If you read the documentation, you'll note that live() was actually used for delegate events like what you're trying to achieve while the bind() method was not; binding events to elements that will be added to the DOM later. The on() function can do this. Either from the document itself or from a direct descendent.
When anchor tag are being created in response of your AJAX call, put id in it like this:
$('body').append("<div class='tag_info' id='myTag'>Some explanations about "+tag_name+"</div>");
and then you can bind event mouseenter or mouseleave like this:
$('#myTag').bind('mouseenter', function(){
alert('Mouse Enter in your Anchor Tag');
}).bind('mouseleave', function(){
alert('Mouse leave');
});

jquery mouseover() isn't working

I've got this bit of jquery which is meant to add class called "wow rubberBand" which is a special class that gives an animation to the element.
However for some reason the animation isn't kicking in.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="wow.min.js"></script>
<script>new WOW().init();</script>
<script type="text/javascript">
$(document).ready(function() {
$("header").mouseover(function() {
$(this).find("span").addClass("wow rubberBand");
})
$("header").mouseout(function() {
$(this).find("span").removeClass("wow rubberBand");
});
});
</script>
Use <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> on the top of the page
There are some basic syntax errors in your code, as #Andreas commented, instead of $(this).attr("class","wow rubberBand"); and $(this).attr("class","");
use
$(this).addClass("wow rubberBand"); and $(this).removeClass("wow rubberBand");
You can chain your mouse events like this:
$thing = $('.thing'); // 'query' for this dom element and cache it - you can do this with your span things for example...
$thing
.on('mouseenter', function() {
$(this).addClass("active");
})
.on('mouseleave', function() {
$(this).removeClass("active");
})
;
// this is the same...
$('.hover-thing').hover( function() {
$(this).toggleClass("blue");
});
https://jsfiddle.net/sheriffderek/b5y6mrb0/
You could also use .hover() or CSS :hover - depending on what you are doing. I very rarely find myself reaching for mouseenter
Despite the comments: $(this).attr('class', ''); and $(this).attr('class', 'className'); - are totally valid ways of changing a class attr. The negative part is that you'll clobber any existing classes if you remove al of them - so removeClass() is a helper that checks for that particular class in the array of classes and removes just that one.
I think it might be because you have to attach the eventhandler on the document, or maybe its just an syntax error ("header" should be ".header")
(function ($) {
$( document ).on( 'mouseenter', '.header', {}, function( e ) {
console.log( "hover" );
});
})(jQuery);

JQuery not removing class?

So, I am trying to create blocks that cycle through some colors. Each color is defined by a class, and I remove a certain class color, then add another class color when a block is clicked. Each segment of code looks like this:
//Function 1
$('.blue').click(function(){
console.log("Blue has been clicked");
$(this).addClass('green');
$(this).removeClass('blue');
});
//Function 2
$('.green').click(function(){
console.log("Green has been clicked");
$(this).addClass('yellow');
$(this).removeClass('green');
});
When a block is clicked a first time, the color is changed. But when I click it again, the color does not change.
I added console.log statements to monitor in Console what was happening. As an example, when I click a box that has the blue class, it adds the green class, and the blue class is removed. But when I click the same box (that is now green) I expect the second function to run, and the box to change into a yellow color. However, what I can see through the console is that the first function is trying to run again.
I checked the HTML, and the classes do change.
My question is, why is function 1 triggered when the first box is no longer a member of the blue class? Should it not be calling function 2, since it is now a member of the green class?
The CodePen is here, I am actively working on it. I will mention here when the CodePen works.
**The CodePen now works, I used $(document).on('click', '.green') instead of $('.green).click() **
Thank you!
Since you want to change the event handlers based on changed selectors you need to use event delegation.
//Function 1
$(document).on('click', '.blue', function () {
console.log("Blue has been clicked");
$(this).addClass('green');
$(this).removeClass('blue');
});
//Function 2
$(document).on('click', '.green', function () {
console.log("Green has been clicked");
$(this).addClass('yellow');
$(this).removeClass('green');
});
In your event registration, the selectors are evaluated only once when the page is loaded, any changes done after that to the classes will not affect the registered handlers.
Code Snippet Example
$(document).on('click', '.blue', function () {
console.log("Blue has been clicked");
$(this).addClass('green');
$(this).removeClass('blue');
});
//Function 2
$(document).on('click', '.green', function () {
console.log("Green has been clicked");
$(this).addClass('yellow');
$(this).removeClass('green');
});
$(document).on('click', '.yellow', function () {
console.log("Yellow has been clicked");
$(this).addClass('blue');
$(this).removeClass('yellow');
});
$(document).on('click', '.red', function () {
console.log("Red has been clicked");
$(this).addClass('blue');
$(this).removeClass('red');
});
.block{
display: inline-block;
width: 200px;
height: 100px;
}
.green{
background-color: green;
}
.blue{
background-color: blue;
}
.yellow{
background-color: yellow;
}
.red{
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='block green'></div>
<div class='block blue'></div>
<div class='block yellow'></div>
<div class='block red'></div>
use on instead of click, because you're changing the class of your div, so you have to use .on() to get the click event bind when it changes the class
//Function 1
$(document).on('click', '.blue', function(){
console.log("Blue has been clicked");
$(this).addClass('green');
$(this).removeClass('blue');
});
//Function 2
$(document).on('click', '.green', function(){
console.log("Green has been clicked");
$(this).addClass('yellow');
$(this).removeClass('green');
});
fiddle
What you are trying to do is this: http://jsfiddle.net/drxzLqrL/1/
$(document).ready(function(){
function foo($elm){
var color = $elm.data('color');
switch (color) {
case 'blue':
$elm.addClass('green')
.removeClass('blue')
.data('color', 'green');
break;
case 'green':
$elm.addClass('yellow')
.removeClass('green')
.data('color', 'yellow');
break;
case 'yellow':
$elm.addClass('red')
.removeClass('yellow')
.data('color', 'red');
break;
case 'red':
$elm.addClass('blue')
.removeClass('red')
.data('color', 'blue');
}
}
$('.block').on('click', function(e){
foo($(e.currentTarget));
});
});
Also use .on() instead of .click(), because you have to get the event when it changes the class and .on() provide you all the functionality of both .bind() and .live()
I hope it's help! :)
You want to use jQuery's .on() instead of the basic event binding:
https://api.jquery.com/on/
You just need to use toggleClass in this case.
FIDDLE
These clicks are binded to the elements only once, so they will not be there when you change the class. Instead, bind the click event to the 'block' class. You might also want to write this a bit more efficiently with switches or if/else.
$(document).ready(function(){
$('.block').click(function(){
if($(this).hasClass('blue'))
{
$(this).addClass('green').removeClass('blue');
}
else if($(this).hasClass('green'))
{
$(this).addClass('yellow').removeClass('green');
}
else if($(this).hasClass('yellow'))
{
$(this).addClass('red').removeClass('yellow');
}
else if($(this).hasClass('red'))
{
$(this).addClass('blue').removeClass('red');
}
$('.block').click(function(){
console.log("Block has been clicked");
});
});
});
You can view it working here:
http://codepen.io/anon/pen/pvGPyx
Lets do something different here. we'll use bind on the function - prior to executing it - to pass in an object parameter, and the scope of the function (this) being the instance handled within the anonymous function, or event delegate handler.
//Common Function
function ChangeState(state, evArg)
{
console.clear();
console.log("this: %o, state: %o, evArg: %o", this, state, evArg);
$(this).addClass(state.new);
$(this).removeClass(state.old);
}
//Function 1
$(document).on("click", ".blue", function(evArg){
ChangeState.bind(this,{"old":"blue","new":"yellow"}, evArg)();
});
$(document).on("click", ".yellow", function(evArg){
ChangeState.bind(this,{"old":"yellow","new":"red"}, evArg)();
});
$(document).on("click", ".red", function(evArg){
ChangeState.bind(this,{"old":"red","new":"green"}, evArg)();
});
$(document).on("click", ".green", function(evArg){
ChangeState.bind(this,{"old":"green","new":"blue"}, evArg)();
});
.block{
display: inline-block;
width: 200px;
height: 100px;
}
.green{
background-color: green;
}
.blue{
background-color: blue;
}
.yellow{
background-color: yellow;
}
.red{
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='block green'></div>
<div class='block blue'></div>
<div class='block yellow'></div>
<div class='block red'></div>

Categories

Resources