Javascript Sticky Notes - javascript

I made some sticky notes in javascript for fun.
When there are multiple sticky notes on the screen, I want the one that is selected to be brought forward. IE. raise the z-index to be higher then the other sticky notes.
Currently I am doing this with CSS using :hover, which is kind of annoying. I want to do it in javascript/jquery. I tried to do addClass/removeClass with focus() and blur()
This is what I have so far
$('.darkYellow').click(function() {
$(this).focus(function() {
$(this).addClass("index");
});
});
$('.darkYellow').blur(function() {
$(this).removeClass("index");
});
Updated and Working thanks to Christoph
http://jsfiddle.net/EnigmaMaster/aQMhk/6/

Class selectors start with a . character, class names do not (well, they can, but that way lies madness).
$(this).addClass("index")

for addClass there is no need to include '.'
Simply
$(this).addClass("index");
http://api.jquery.com/addClass/

Though at the moment I don't know, why .on() does not work (this shoud be the preferred method!), the following code should work:
$('.darkYellow').live("click", function() {
$(".index").removeClass("index");
$(this).addClass("index");
});
This is all you need.
live event handler on click ( use of on() should be preferred )
look for index note and remove class
add Class to current "clicked" element
DEMO

You're calling $('.darkYellow').click() before the sticky notes actually exist. .click() will add an event to each element that matches the selector at the time of calling. What you want is something like .live() which will handle all elements, present and future E.g.
$('.darkYellow').live('click', function() {
$(this).focus(function() {
$(this).addClass("index");
});
});
UPDATE
Try:
$('.darkYellow').live('click', function() {
$(this).addClass("index");
});
$('.darkYellow').live('blur', function() {
$(this).removeClass("index");
});
As someone else pointed out, the call to .focus() should be unnecessary.

Here's a toggleFocus() function I recently wrote, it's designed to add a .is-focused class the parentNode on focus/blur events.
CodePen Demo
function toggleFocus(e) {
setTimeout(() => {
e.addEventListener('focus', ({path}) => {
path[2].classList.add("is-focused");
}, true);
e.addEventListener('blur', ({path}) => {
path[2].classList.remove("is-focused");
}, true);
}, 0);
}
const items = document.getElementById('items');
const itemsArray = items.querySelectorAll(".item");
[].forEach.call(itemsArray, (item) => {
toggleFocus(item)
});

Related

how to bind 2 elements in jquery on click function

For closing a modal with the class submitmodal i use this code and it works fine.
$('.submitmodal').click(function() {
window.location.hash='close';
});
For click on the body somewhere i use this:
$('body').click(function() {
window.location.hash='close';
});
How can i merge them together?
I tried this but it does not work
$('.submitmodal', 'body').click(function() {
window.location.hash='close';
});
Try
(".submitmodal, body").click(function() {
window.location.hash="close";
});
The selectors have to be in the same string, seperated by a comma.
Try this :
$(document).on("click",'body',function(){
window.location.hash='close';
})
This should do it
$('.submitmodal, body').click(function() {
window.location.hash = 'close';
});
You can use Multiple selector using first selector, second selector
$('body,.submitmodal').click(function() {
window.location.hash='close';
});
You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.
$("body, .submitmodal").click(function() {
window.location.hash="close";
});
For More help see this : multiple-selector
I hope it helps you :), Thanks.
This should solve your issue:
$('.submitmodal, body').click(function() {
window.location.hash='close';
});
But the problem I see is that when you click anywhere over the body you are closing your modal and that includes when you click over the element that opens itself. So I would suggest you to write something like that:
$('body, .submitmodal').click(function(e) {
if (e.target !== this) return; //prevents body's child elements from being affected
window.location.hash='close';
});
I've done some tests and apparently 'this' references to the first selector (body) which is fine for this situation.

Issue regarding javascript function not firing on hover of div

I have a use case whereby i know that all the divs i am interested in will have the word 'tabz' in them but have yet to find a way to fire my jquery when a user clicks on a div with such an id.
$('div[id=*"tabz"]').on("click", function()
{
alert(event.target.id);
});
This is what i have however the alert never fires.
When I replace the method with :
$('div').on("click", function()
{
alert(event.target.id);
});
it will give me the following:
tabz91
So i know there are divs that meet my selector but it I am unsure as to why the alert is not firing.
Any help greatly appreciated
The correct syntax is simply
$('div[id*="tabz"]')
(the = and the * are inverted in your example).
You may use
$('div[id$="tabz"]')
if the id attribute ends with your pattern.
$('div[id*="tabz"]').on("click", function()
{
alert(event.target.id);
});
It's a typo, * and = inverted. See this example : http://jsfiddle.net/Xcn6N/
try instead of =* it is *=
$('div[id*="tabz"]').on("click", function() {
alert(event.target.id);
});
For Further Assistance on Selectors in jQuery see this page
jQuery Selectors

How to toggle an element with on()?

I am using the Hammer.js library for mobile touch events and in their example for use with jQuery, they have the following:
$('#test_el').hammer().on("tap", ".nested_el", function(event) {
console.log(this, event);
});
This is straightforward; however, I would like to incorporate a toggle behavior to #test_el. In other words, if the above example was replaced with something like this:
$('button').hammer().on("tap", function() {
$('div').addClass('open');
}, function {
$('div').addClass('close');
});
How would I get this "toggle" behavior to work?
Initially, you could add a starting class to all buttons. Then on event, you can check if the class exists. This lets you know what state the element was in when you tapped it.
$('button').addClass('close');
$('button').hammer().on('tap', function() {
if ($(this).hasClass('close')) {
$(this).removeClass('close').addClass('open');
// Event code
}
else {
$(this).removeClass('open').addClass('close');
// Event code
}
});
jQuery also provides a toggleClass method.
There is already a toggleClass function available in JQuery, it seems that it does what you want.
Try:
$('#test_el').hammer().on("tap", ".nested_el", function(event) {
$(this).toggleClass("classnamehere");
});
Where classnamehere would be your class name.

Correct usage of jQuery toggle method

$('#btn2').toggle(
function () {
$('#btn2').text('show');
},
function () {
$('#btn2').text('hide');
}
)
This does not work on my computer (on any browser). Could this be due to a change in the method between jQuery versions?
See fiddle
This functionality of .toggle was removed in jQuery 1.9
So this wont work for jQuery 1.9 or later..
See one alternative here
Per your updated feature request, to simply alternate between two inner text values:
$('#btn2').click(function() {
$(this).text( $(this).text()=='show'? 'hide':'show' );
});
That is not one of the signatures of toggle. To use its hide/show capabilities, do this $(elem).toggle() (and obviously if the button is hidden it can't say 'show', so presumably you're toggling something else):
$(elem).toggle();
$('#btn2').text( $(elem).is(':visible') ? 'hide' : 'show' );
Try this: http://jsfiddle.net/W9JCR/
$('#btn2').click(function () {
($(this).text()=='show') ? $(this).text('hide') : $(this).text('show');
});
Yes, it's still supported. I think the problem with your code is that you've used text(). Use val()
$('#btn2').toggle(function () {
$('#btn2').val('show');
},function () {
$('#btn2').val('hide');
});

Detect IF hovering over element with jQuery

I'm not looking for an action to call when hovering, but instead a way to tell if an element is being hovered over currently. For instance:
$('#elem').mouseIsOver(); // returns true or false
Is there a jQuery method that accomplishes this?
Original (And Correct) Answer:
You can use is() and check for the selector :hover.
var isHovered = $('#elem').is(":hover"); // returns true or false
Example: http://jsfiddle.net/Meligy/2kyaJ/3/
(This only works when the selector matches ONE element max. See Edit 3 for more)
.
Edit 1 (June 29, 2013): (Applicable to jQuery 1.9.x only, as it works with 1.10+, see next Edit 2)
This answer was the best solution at the time the question was answered. This ':hover' selector was removed with the .hover() method removal in jQuery 1.9.x.
Interestingly a recent answer by "allicarn" shows it's possible to use :hover as CSS selector (vs. Sizzle) when you prefix it with a selector $($(this).selector + ":hover").length > 0, and it seems to work!
Also, hoverIntent plugin mentioned in a another answer looks very nice as well.
Edit 2 (September 21, 2013): .is(":hover") works
Based on another comment I have noticed that the original way I posted, .is(":hover"), actually still works in jQuery, so.
It worked in jQuery 1.7.x.
It stopped working in 1.9.1, when someone reported it to me, and we all thought it was related to jQuery removing the hover alias for event handling in that version.
It worked again in jQuery 1.10.1 and 2.0.2 (maybe 2.0.x), which suggests that the failure in 1.9.x was a bug or so not an intentional behaviour as we thought in the previous point.
If you want to test this in a particular jQuery version, just open the JSFidlle example at the beginning of this answer, change to the desired jQuery version and click "Run". If the colour changes on hover, it works.
.
Edit 3 (March 9, 2014): It only works when the jQuery sequence contains a single element
As shown by #Wilmer in the comments, he has a fiddle which doesn't even work against jQuery versions I and others here tested it against. When I tried to find what's special about his case I noticed that he was trying to check multiple elements at a time. This was throwing Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: hover.
So, working with his fiddle, this does NOT work:
var isHovered = !!$('#up, #down').filter(":hover").length;
While this DOES work:
var isHovered = !!$('#up,#down').
filter(function() { return $(this).is(":hover"); }).length;
It also works with jQuery sequences that contain a single element, like if the original selector matched only one element, or if you called .first() on the results, etc.
This is also referenced at my JavaScript + Web Dev Tips & Resources Newsletter.
Use:
var hovered = $("#parent").find("#element:hover").length;
jQuery 1.9+
It does not work in jQuery 1.9. Made this plugin based on user2444818's answer.
jQuery.fn.mouseIsOver = function () {
return $(this).parent().find($(this).selector + ":hover").length > 0;
};
http://jsfiddle.net/Wp2v4/1/
The accepted answer didn't work for me on JQuery 2.x
.is(":hover") returns false on every call.
I ended up with a pretty simple solution that works:
function isHovered(selector) {
return $(selector+":hover").length > 0
}
Set a flag on hover:
var over = false;
$('#elem').hover(function() {
over = true;
},
function () {
over = false;
});
Then just check your flag.
Couple updates to add after working on this subject for a while:
all solutions with .is(":hover") break on jQuery 1.9.1
The most likely reason to check if the mouse is still over an element is to attempt to prevent events firing over each other. For example, we were having issues with our mouseleave being triggered and completed before our mouseenter event even completed. Of course this was because of a quick mouse movement.
We used hoverIntent https://github.com/briancherne/jquery-hoverIntent to solve the issue for us. Essentially it triggers if the mouse movement is more deliberate. (one thing to note is that it will trigger on both mouse entering an element and leaving - if you only want to use one pass the constructor an empty function )
You can filter your elment from all hovered elements.
Problematic code:
element.filter(':hover')
Save code:
jQuery(':hover').filter(element)
To return boolean:
jQuery(':hover').filter(element).length===0
Expanding on #Mohamed's answer. You could use a little encapsulation
Like this:
jQuery.fn.mouseIsOver = function () {
if($(this[0]).is(":hover"))
{
return true;
}
return false;
};
Use it like:
$("#elem").mouseIsOver();//returns true or false
Forked the fiddle:
http://jsfiddle.net/cgWdF/1/
I like the first response, but for me it's weird. When attempting to check just after page load for the mouse, I have to put in at least a 500 millisecond delay for it to work:
$(window).on('load', function() {
setTimeout(function() {
$('img:hover').fadeOut().fadeIn();
}, 500);
});
http://codepen.io/molokoloco/pen/Grvkx/
https://api.jquery.com/hover/
Asynchronous function in line 38:
$( ".class#id" ).hover(function() {
Your javascript
});
Setting a flag per kinakuta's answer seems reasonable, you can put a listener on the body so you can check if any element is being hovered over at a particular instant.
However, how do you want to deal with child nodes? You should perhaps check if the element is an ancestor of the currently hovered element.
<script>
var isOver = (function() {
var overElement;
return {
// Set the "over" element
set: function(e) {
overElement = e.target || e.srcElement;
},
// Return the current "over" element
get: function() {
return overElement;
},
// Check if element is the current "over" element
check: function(element) {
return element == overElement;
},
// Check if element is, or an ancestor of, the
// current "over" element
checkAll: function(element) {
while (overElement.parentNode) {
if (element == overElement) return true;
overElement = overElement.parentNode;
}
return false;
}
};
}());
// Check every second if p0 is being hovered over
window.setInterval( function() {
var el = document.getElementById('p0');
document.getElementById('msg').innerHTML = isOver.checkAll(el);
}, 1000);
</script>
<body onmouseover="isOver.set(event);">
<div>Here is a div
<p id="p0">Here is a p in the div<span> here is a span in the p</span> foo bar </p>
</div>
<div id="msg"></div>
</body>

Categories