This question already has an answer here:
What to use instead of `toggle(...)` in jQuery > 1.8?
(1 answer)
Closed 6 years ago.
Currently as per Jquery site .toggle() has been depreciated after 1.8 version. So is there any alternative to .toggle() as i need the function for menu app in which I need to hide and show contents of a div based on button click
I have already accomplished the task according to JSFiddle but I am already loading 1.12.4 version of jquery on my site for other usage
my Js function code
function hideToggle(button, elem) {
$(button).toggle(
function() {
$(elem).hide();
},
function() {
$(elem).show();
} );
}
hideToggle(".button1", ".iframe1");
So is there a way to prevent loading two versions of jquery
This is basically what hide and show are doing.
CSS
.hidden {
display:none;
/* you could also use !important here */
}
JQuery
$('#someElement').toggleClass('hidden');
They do not seem to have replaced it with an equivalent method. However, you can do this:
$(button).on('click', function() {
if ($(elem).is(':visible') { // if $(elem) is visible
$(elem).hide(); / hide it
} else { // if not
$(elem).show(); // show it
}
Bizarrely, the simple solution to this is a different toggle function. This function toggles the display of the element.
Your function could be simplified to
function hideToggle(button, elem) {
$(button).click(
function() {
$(elem).toggle();
}
);
}
You can call .toggle() on click to achieve exactly the same thing:
$(".button1").click(function() { $(".iframe1").toggle();});
$(".button2").click(function() { $(".iframe2").toggle();});
Updated fiddle: https://jsfiddle.net/6g3cko1h/3/ including an updated version of your utility-style setup method:
function hideToggle(button, elem)
{
$(button).click(function() { $(elem).toggle(); })
}
You are not understanding right what was deprecated. The toggle function is valid.
Which is "Display or hide the matched elements".
The current documentation for toggle is - http://api.jquery.com/toggle/
so
$('button').toggle()
Would hide the element if it was visible, or show it - if it was visible
Related
I want to toggle text between bold and normal I made this code for it, but when I open my page the bold button disappears?
$("#bold").toggle(function() {
$('.focus').css("font-weight", $(this).val());
}, function() {
$('.focus').css("font-weight", "normal");
});
Is there something wrong with my code?
Please help, thanks in advance.
Assuming you're using jQuery 1.9 or later the problem is that the .toggle() event handling method was removed from the library. So what you're actually calling is the .toggle() function that hides/shows elements. (In earlier versions of jQuery both functions existed and jQuery figured out which one you meant based on the arguments passed in.)
You can implement your own toggle easily enough with a standard .click() handler:
$("#bold").click(function() {
var f = !$(this).data("toggleFlag");
if (f) {
$('.focus').css("font-weight", $(this).val());
} else {
$('.focus').css("font-weight", "normal");
}
$(this).data("toggleFlag", f);
});
This uses the .data() method to keep track of a boolean flag to indicate which code to execute. The very first time the click handler is called the flag will be returned as undefined because it hasn't previously been set, but we just convert that to a boolean with ! (assuming you want to execute the if and not the else case on the first click).
It disappears because that version of toggle is deprecated and removed, and in newer versions of jQuery all it does is toggle visibility.
You could do something like this instead :
var state = true;
$("#bold").on('click', function() {
$('.focus').css("font-weight", state ? this.value : 'normal');
state = !state;
});
FIDDLE
The only solution I fount to the disappearing element after click... is Callback function after the toggle effect finished.
here a link that explain the Callback function.
and here is my code:
jQuery('.menu li.item-487').click(function(){
jQuery('#main-menu .moduletable .menu li').toggle("slow",function(){jQuery('.menu li.item-487').css('display' , 'block');});
});
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.
$('#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');
});
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)
});
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>