So I have this simple HTML
<div class="song">
<img src="http://o.scdn.co/300/40e3ec60c92513f724f47ce71baad1e496627107">
</div>
And this simple jQuery
$(".song").on( "mouseenter", function() {
$(this).css( "background-color", "red" );
alert('bla');
});
And the event does not fire.
Although
$(".naujienuKategorija").on( "mouseenter", function() {
$(this).css( "background-color", "red" );
});
Works just fine on
<p class="naujienuKategorija">Apklausa</p>
Which is on the same page.
.song has the following css
.song {
padding-bottom: 12px;
margin-bottom: 15px;
border-bottom: 1px solid #E0E0E0;
overflow: hidden;
}
I am obviously missing something... obvious.
In order for an event to be bound to an element, the element has to be ready and found. A general way to do this is to put your event bindings inside of $(document).ready because it ensures original elements on the page can be accessed. So use this:
$(document).ready(function () {
$(".song").on( "mouseenter", function() {
$(this).css( "background-color", "red" );
alert('bla');
});
});
Another option is to put your event binding on the page at any time after the target elements, either immediately or right before the </body>. For example:
<div class="song"></div>
<div class="song></div>
<script type="text/javascript">
$(".song").on("mouseenter", function () {
});
</script>
It might've been working with the .naujienuKategorija elements because you were using the second method above, but weren't with the .song elements.
Related
When a use moves their mouse on a webpage, I want to track that. Then I want to unbind that listener so that mousemove no longer gets tracked. How can I do that? The code below does not seem to work.
var clearIdleInterval = function () {
console.dir('unbind');
clearInterval(this.idleInterval);
$(document).unbind('mousemove', clearIdleInterval.bind(this));
$(document).unbind('keypress', clearIdleInterval.bind(this));
};
$(document).bind('mousemove', clearIdleInterval.bind(this));
$(document).bind('keypress', clearIdleInterval.bind(this));
Use .unbind() to unbind events. As shown below.
Note: If you want to unbind mousemove event for specific elements, and avoid to affect other handlers, you can do that too. For example
$( "#foo" ).unbind( "mousemove.myEvents" );
It is documented really well here
Hope that was helpful.
$(document).bind('mousemove', function(e){
$(".test").html(`${e.clientX} , ${e.clientY}`)
});
function unBind(){
$(document).unbind( "mousemove" );
}
.test{
text-align: center;
vertical-align: middle;
line-height: 90px;
height : 200px;
width : 200px;
border : solid;
margin-top : 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button onclick="unBind()">Un Bind</button>
<div class="test"></div>
I'm taking by first babysteps in jQuery and stumbled upon a problem I can't seem to get around.
I couldn't find an article that quite described what my problem was, so I would like to try to get an answer this way.
I don't understand why my objects keep behaving like their former class.
When I setup a hover action for a class, and change the class of the object by clicking, jQuery keeps doing the animation for the new class.
I used toggleClass() and removeClass/ addClasswithout any result:
https://jsfiddle.net/biest9160/f0na6sro/
var wide = function() {
$(this).animate({ 'width': '120px' }, 200);
}
var normal = function() {
$(this).animate({ 'width': '100px' }, 200);
}
$(document).ready(function() {
$('.class1').hover(wide, normal);
$('.class1').click(function() {
$(this).toggleClass('class1 class2');
})
})
div {
width: 100px;
height: 100px;
border: 1px solid #000;
margin: auto;
}
.class2 {
background: #555;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box1" class="class1">box1</div>
<div id="box1" class="class1">box2</div>
<div id="box1" class="class1">box3</div>
<div id="box1" class="class1">box4</div>
I don't understand why the the hover action is triggered while the object has a new class.
Initialy you attach the event to the element with the class name. After the class is changed the event remains on the element.
To remove the event you can use .unbind. To remove .hover event you can check this answer.
A working example using .unbind to remove the event and after to reattach it will look like in the snippet (basically is toggle hover event):
var wide = function(){
$(this).animate({'width':'120px'},200);
}
var normal = function(){
$(this).animate({'width' : '100px'},200);
}
$(document).ready(function(){
$('.class1').hover(wide,normal);
$('.class1').click(function(event){
var $this = $(this);
$this.unbind('mouseenter mouseleave'); // remove hover
if( $this.hasClass('class2'))
{
$this.hover(wide, normal); // reattach hover
}
$this.toggleClass('class1 class2');
})
})
div{
width:100px;
height:100px;
border: 1px solid #000;
margin: auto;
}
.class2{
background: #555;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box1" class="class1">box1</div>
<div id="box1" class="class1">box2</div>
<div id="box1" class="class1">box3</div>
<div id="box1" class="class1">box4</div>
Use .on() menthod to bind the event which will actually bind the event on the parent of the class.
Here is the example:
$(document).on("click", '.class1', function(){
$(this).toggleClass('class1 class2');
});
This will defiantly work...
I'm appending some text onto a div using a button, and want something to happen when you hover over it (after it's been appended). I tried using .on('hover' '.class') but so far haven't been able to get it to work. Any help would be appreciated.
Here's an example of what I'm talking about (I want something to happen when you hover YOU CLICKED ME!).
var text = "YOU CLICKED ME"
$(".button").click(function () {
$(".receiver").append('<a class="appendage">'+text+'</a>');
});
$('.receiver').on('hover', '.appendage', function(){
$(".tooltip").append('<a class="tooltip">'+text+'</a>');
});
.receiver {
height:300px;
border: 1px solid black;
}
.tooltip {
height:300px;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='button'>CLICK ME</div>
<div class='receiver'></div>
<div class='tooltip'></div>
The 'hover' pseudo-event is obsolete and removed since jQuery 1.9. Use 'mouseenter mouseleave' instead, or just 'mouseenter' as may be preferable.
Excerpt from jQuery.on documentation:
Deprecated in jQuery 1.8, removed in 1.9: The name "hover" used as a shorthand for the string "mouseenter mouseleave". It attaches a single event handler for those two events, and the handler must examine event.type to determine whether the event is mouseenter or mouseleave. Do not confuse the "hover" pseudo-event-name with the .hover() method, which accepts one or two functions.
Working Example:
var text = "YOU CLICKED ME"
$(".button").click(function () {
$(".receiver").append('<a class="appendage">'+text+'</a>');
});
$('.receiver').on('mouseenter mouseleave', '.appendage', function(){
$(".tooltip").append('<a class="tooltip">'+text+'</a>');
});
.receiver {
height:300px;
border: 1px solid black;
}
.tooltip {
height:300px;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='button'>CLICK ME</div>
<div class='receiver'></div>
<div class='tooltip'></div>
Use mouseover or mouseenter instead of hover. .on('hover') was deprecated in jQuery 1.8, and removed in 1.9.
$('.receiver').on('mouseover', ...
http://api.jquery.com/on/
Deprecated in jQuery 1.8, removed in 1.9: The name "hover" used as a shorthand for the string "mouseenter mouseleave". It attaches a single event handler for those two events, and the handler must examine event.type to determine whether the event is mouseenter or mouseleave. Do not confuse the "hover" pseudo-event-name with the .hover() method, which accepts one or two functions.
var text = "YOU CLICKED ME"
$(".button").click(function () {
$(".receiver").append('<a class="appendage">'+text+'</a>');
});
$('.receiver').on('mouseenter','.appendage', function(){
$(".tooltip").append('<a class="tooltip">'+text+'</a>');
});
.receiver {
height:300px;
border: 1px solid black;
}
.tooltip {
height:300px;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='button'>CLICK ME</div>
<div class='receiver'></div>
<div class='tooltip'></div>
I'm working on my mobile portfolio (http://lehuagray.com/mobile). Right now a user can flip forward and backward through my images by either sliding or using the buttons. As the user flips, the class .main is removed from their current image and transferred to either the previous or next image. But if the user flips backwards from the first slide or forward from the last slide, .main doesn't have a target to be transferred to. It falls off the edge, and the slide show ceases to function.
The HTML is just a series of divs inside a container. The CSS is probably totally inconsequential except maybe that I had to use z-index to reverse the order of the slide layers (which are absolutely positioned and stacked). Here is a jsfiddle: http://jsfiddle.net/v4b8S/4/. It doesn't matter what the events are, the problem isn't in the events, so I gave the jsfiddle some buttons for ease.
Here is my jQuery code it it's most basic, everything else is just a variation on this:
$( "#rolodexnarrow" ).bind( "swipeleft", function(event) {
$( this ).hide("blind", function() {
$ ( this ).removeClass("main").next().addClass("main")
});
});
$( "#rolodexnarrow" ).bind( "swiperight", function(event) {
$ ( this ).removeClass("main").prev().addClass("main");
$( this ).prev().show("blind");
});
I've tried an if statement:
$( "#rolodexnarrow" ).bind( "swipedown", function(event) {
$( ".main" ).prev().show("blind");
if ( $(".main").is("#slide1") == false ){
$ ( ".main" ).removeClass("main").prev().addClass("main");
}
});
Counter-intuitively (to me at least), this just makes the first and last slides no longer show/hide and no longer receive the .main class, so we get stuck with the second and second-to-last slides up. I have also tried an if statement using (":first"). This is obviously a pretty simple slide show, I'm sure there is a simple solution. I'm sure, also, that this is something that everyone else already knows how to fix but I can't find anything about it since I'm not even really sure what to search for.
Noe: The swipe is a touch interface and barely works on a mouse, especially since everything is linked to lightboxes. If you use a touch device, it doesn't have that problem.
Here you go: http://jsfiddle.net/v4b8S/6/
Here is the updated JS code:
$( ".container" ).bind( "click", function(event) {
if(!$(".main").is("#slide4")) {
$( ".main" ).hide("blind", function() {
$ ( this ).removeClass("main").next().addClass("main");
});
}
});
$(".container").on( "dblclick", function(event) {
if( !$(".main").is("#slide1")) {
$(".main").prev().show("blind");
$(".main").removeClass("main").prev().addClass("main");
}
});
UPDATE1:
Also, read jquery's dblclick event and its handling. In particular, notice that adding handlers for both the click and the dblclick event are not suggested since which one will be triggered first is highly browser and machine dependent. I guess that'll not be a problem for your usecase since you are going to change it to swipe events. (For me, I had to manually trigger the dblclick event using browser console.)
UPDATE2:
The dblclick event handler is also working fine now. I had to change the order of things there.
UPDATE3:
I didn't see your new fiddle till now. Basically it's the same code as above but is activated on the click of the forward and backward buttons.
/*code with if statement, if you want to play with that
$( ".forward" ).bind( "click", function() {
if ( $(".main").is("#slide4") == false ){
$( ".main" ).hide("blind", function() {
$ ( this ).removeClass("main").next().addClass("main")
});
}
});
$( ".backward" ).bind( "click", function() {
$( ".main" ).prev().show("blind");
if ( $(".main").is("#slide1") == false ){
$ ( ".main" ).removeClass("main").prev().addClass("main");
}
});
*/
//simple code
$(".forward").click(function() {
if (!$(".main").is("#slide4")) {
$(".main").hide("blind", function() {
$(this).removeClass("main").next().addClass("main");
});
}
});
$(".backward").click(function() {
if (!$(".main").is("#slide1")) {
$(".main").prev().show("blind");
$(".main").removeClass("main").prev().addClass("main");
}
});
.container {
width: 400px;
height: 400px;
position: relative;
}
.slide {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
#slide1 {
background-color: blue;
z-index: 5;
}
#slide2 {
background-color: green;
z-index: 4;
}
#slide3 {
background-color: yellow;
z-index: 3;
}
#slide4 {
background-color: orange;
z-index: 2;
}
.button {
padding: 14px 7px;
width: 20%;
margin: 20px;
display: inline-block;
background-color: #ccc;
}
.main {
z-index: 10;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="slide main" id="slide1"></div>
<div class="slide" id="slide2"></div>
<div class="slide" id="slide3"></div>
<div class="slide" id="slide4"></div>
</div>
<div class="forward button">forward</div>
<div class="backward button">backward</div>
The question of how to detect a click on anywhere except a specified element has been answered a couple of items like here:
Event on a click everywhere on the page outside of the specific div
The problem I have is trying to figure out how to detect a click anywhere except a given element including one of it's children.
For example in this code:
http://jsfiddle.net/K5cEm/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$(function() {
$(document).click(function(e) {
$('#somediv').hide();
});
$('#somediv').click(function(e) {
e.stopPropagation();
});
});
</script>
<div style="border: 1px solid red; width:100px; height: 100px" id="somediv">
<span style="display: block; border: 1px solid green; width:50px; height: 50px; margin: 0 auto" id="someSpan"></span>
</div>
Clicking anywhere outside the red div should cause it to hide. Not only that but also clicking on it's child element (the green span) should cause it to hide. The only time it shouldn't hide is if you click on it but not on the span. As it stands now, the click on the span is also considered a click on the parent div hence it doesn't hide the div if the span is clicked.
How to achieve this?
You can compare the click's target to the element in question:
$(document).click(function(e) {
if (e.target != $('#somediv')[0]) {
$('#somediv').hide();
}
});
Demo: http://jsfiddle.net/K5cEm/7/
Add this:
$('#somediv').click(function(e) {
e.stopPropagation();
}).children().click(function(e) {
$('#somediv').hide();
});
Here's your updated working fiddle: http://jsfiddle.net/K5cEm/5/
I'd do it like so:
$(function () {
var elem = $( '#somediv' )[0];
$( document ).click( function ( e ) {
if ( e.target !== elem ) {
$( elem ).hide();
}
});
});
Live demo: http://jsfiddle.net/uMLrC/
So this
var elem = $( '#somediv' )[0];
caches the reference to the DIV element. We want to cache this reference on page load, so that we don't have to query for that element repeatedly. And it improves the readability of the code, also.