Jquery mouse enter and mouse leave not working on li element - javascript

I am trying to use jquery mouse enter and mouse leave functions .
this is my code :
html :
<ul class="menuList bold">
<li id="tevee">
<span>test</span>
</li>
</ul>
jquery
$(function(){
$(".tevee").on("mouseenter",".menuList",hoverInFunction());
$(".tevee").mouseleave(hoverOutFunction("tevee"));
});
function hoverInFunction()
{
alert("hi")
}
function hoverOutFunction(variable)
{
alert("test");
}
https://jsfiddle.net/tejareddy/dndvsudh/ . this is my fiddle , they are not working instead they are triggering on page load and not every time when i hover on them .

Remove the ()
change
$(function(){
$("#tevee").on("mouseenter",".menuList",hoverInFunction());
});
to:
$(function(){
$("#tevee").on("mouseenter",".menuList",hoverInFunction)
});
or do it like this:
$("#tevee").on("mouseenter",".menuList",function(){
alert("hi")
}).on("mouseleave",".menuList", function(){
alert("test");
});

Firstly, your selector was incorrect for the ".on" call, secondly, you were using parenthesis when referring to a function (which in this case must be referred to as an object without the parenthesis).
$(function(){
$(".menuList").on("mouseenter","li",hoverInFunction);
$(".menuList").on("mouseleave","li",hoverOutFunction);
})
Please see the fixed version here
You may use event.data if you wish to pass parameters into the calls.
The original method of binding the event to the ID is not what .on is all about, it's best to bind to a higher-level object in the DOM (such as the actual menuList) and then write a selector which will affect the children on it. That way you get "delegated eventing" and any dynamically added items will still work the way you want them to.

Related

JavaScript event execute immediately after bind? [duplicate]

I have a link:
<ul id="titleee" class="gallery">
<li>
Talent
</li>
</ul>
and I am trying to trigger it by using:
$(document).ready(function() {
$('#titleee').find('a').trigger('click');
});
But it doesn't work.
I've also tried: $('#titleee a').trigger('click');
Edit:
I actually need to trigger whatever get's called here <a href="#inline" rel="prettyPhoto">
If you are trying to trigger an event on the anchor, then the code you have will work I recreated your example in jsfiddle with an added eventHandler so you can see that it works:
$(document).on("click", "a", function(){
$(this).text("It works!");
});
$(document).ready(function(){
$("a").trigger("click");
});
Are you trying to cause the user to navigate to a certain point on the webpage by clicking the anchor, or are you trying to trigger events bound to it? Maybe you haven't actually bound the click event successfully to the event?
Also this:
$('#titleee').find('a').trigger('click');
is the equivalent of this:
$('#titleee a').trigger('click');
No need to call find. :)
Sorry, but the event handler is really not needed. What you do need is another element within the tag to click on.
<a id="test1" href="javascript:alert('test1')">TEST1</a>
<a id="test2" href="javascript:alert('test2')"><span>TEST2</span></a>
Jquery:
$('#test1').trigger('click'); // Nothing
$('#test2').find('span').trigger('click'); // Works
$('#test2 span').trigger('click'); // Also Works
This is all about what you are clicking and it is not the tag but the thing within it. Unfortunately, bare text does not seem to be recognised by JQuery, but it is by vanilla javascript:
document.getElementById('test1').click(); // Works!
Or by accessing the jQuery object as an array
$('#test1')[0].click(); // Works too!!!
Since this question is ranked #1 in Google for "triggering a click on an <a> element" and no answer actually mentions how you do that, this is how you do it:
$('#titleee a')[0].click();
Explanation: you trigger a click on the underlying html-element, not the jQuery-object.
You're welcome googlers :)
If you are trying to trigger an event on the anchor, then the code you have will work.
$(document).ready(function() {
$('a#titleee').trigger('click');
});
OR
$(document).ready(function() {
$('#titleee li a[href="#inline"]').click();
});
OR
$(document).ready(function() {
$('ul#titleee li a[href="#inline"]').click();
});
With the code you provided, you cannot expect anything to happen. I second #mashappslabs : first add an event handler :
$("selector").click(function() {
console.log("element was clicked"); // or alert("click");
});
then trigger your event :
$("selector").click(); //or
$("selector").trigger("click");
and you should see the message in your console.
Well you have to setup the click event first then you can trigger it and see what happens:
//good habits first let's cache our selector
var $myLink = $('#titleee').find('a');
$myLink.click(function (evt) {
evt.preventDefault();
alert($(this).attr('href'));
});
// now the manual trigger
$myLink.trigger('click');
This is the demo how to trigger event
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("input").select(function(){
$("input").after(" Text marked!");
});
$("button").click(function(){
$("input").trigger("select");
});
});
</script>
</head>
<body>
<input type="text" value="Hello World"><br><br>
<button>Trigger the select event for the input field</button>
</body>
</html>
This doesn't exactly answer your question, but will get you the same result with less headache.
I always have my click events call methods that contain all the logic I would like to execute. So that I can just call the method directly if I want to perform the action without an actual click.
For links this should work:
eval($(selector).attr('href'));
You should call the element's native .click() method or use the createEvent API.
For more info, please visit: https://learn.jquery.com/events/triggering-event-handlers/
We can do it in many ways...
CASE - 1
We can use trigger like this : $("#myID").trigger("click");
CASE - 2
We can use click() function like this : $("#myID").click();
CASE - 3
If we want to write function on programmatically click then..
$("#myID").click(function() {
console.log("Clicked");
// Do here whatever you want
});
CASE - 4
// Triggering a native browser event using the simulate plugin
$("#myID").simulate( "click" );
Also you can refer this : https://learn.jquery.com/events/triggering-event-handlers/
Shortest answer:
$('#titlee a').click();

Ignoring certain variables in a jquery

There's a javascript code in the steam blotter page ( the page with activity and other stuff ) and javascript:
(function() {
jQuery(".btn_grey_grey.btn_small_thin.ico_hover").map(function(){
this.click()
});
})().
I want it to ignore "btn_grey_grey.btn_small_thin.ico_hover.active" and only click on btn_grey_grey.btn_small_thin.ico_hover. Is it possible to do that? The current code clicks on the active ones and inactive buttons. Double quotes doesn't seem to change anything.
Use :not selector and each instead of map (it's used for different purposes):
jQuery(".btn_grey_grey.btn_small_thin.ico_hover:not(.active)").each(function() {
this.click();
});
Note also that if you bind event handlers with jQuery you can try simpler expression:
jQuery(".btn_grey_grey.btn_small_thin.ico_hover:not(.active)").click();

Swapping a CSS class on jQuery .load event

I have a list styled with CSS - standard stuff. The items within that feature jQuery .load to load the relevant info into another div. This works fine, however I also need to change the class in the list to reflect which item has been loaded. My existing code below, which will probably explain it better...
<ul class="inner-nav" id="tdlists">
<li class="active"><a onclick="$('##showlist').load('/lists/?List=#ListID#');">#ListName#</a></li>
<li><a onclick="$('##showlist').load('/lists/?List=#ListID#');">#ListName#</a></li>
<li><a onclick="$('##showlist').load('/lists/?List=#ListID#');">#ListName</a></li>
</ul>
The actual list is populated by a db query, however I've stripped that out as I don't believe it's relevant to the question and would only complicate matters!
You can take advantage of the this context set by jQuery for the load callback. For example:
$('#showlist').load('/lists/?List=#ListID#', function(){
$(this).addClass('loaded')
});
As a additional tip, is better if you use event delegation instead of writing the onclick attribute for each li tag:
$('#tdlists').on('click', 'li a', function () {
$('#showlist').load('/lists/?List=#ListID#', function(){
$(this).addClass('loaded')
});
}
The .load() event should have an event handler that will fire when the event is triggered, so you could set your class in there.
$('#showlist').load('/lists/?List=#ListID#',
function(){
//Add class or perform your logic here
$('#showlist').addClass(x););
}
);
.Load() | jQuery API
jQuery.load can be passed a callback method which runs on completion. This could then update the class on the parent.
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});

jquery .live() and .append()

So I'm currently using .append() to add a feature to all of the posts on a webpage, but when additional posts are loaded on the page, the appended features aren't included in the new content — I'm trying to come up with a way to make sure all of the new content has the appended feature too.
$(this).append('<div id="new_feature></div>');
Something like this?
$(this).live().append('<div id="new_feature></div>');
Maybe there's a way to make it constantly appending in a loop perhaps?
There is DOMNodeInserted event:
$('button').click(function() {
$('#appendme').append($('<div class="inner">').text(Math.random()));
})
$('#appendme').on('DOMNodeInserted','.inner',function() {
console.log(this);
});
DEMO
update: this seems not works in IE, try propertychnage event handler also ($('#appendme').on('DOMNodeInserted,propertychange') but i not sure, have no IE to check this right now.
update2: Domnode* seems deprecated according to mdn, they tell to use MutationObserver object instead
update3: seems here is no very crossbrowser solution for MutationEvents, see this answer, so my suggestion would be use code above, if event supported and fallback to setTimeOut or livequery option.
update4:
If you depend only on .append() you can patch jQuery.fn.append() like this:
jQuery.fn.append=function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.appendChild( elem );
$(elem).trigger('appended');
}
});
};
$('button').click(function() {
$('#appendme').append($('<div class="inner">').text(Math.random()));
})
$('#appendme').on('appended','.inner',function() {
console.log(this);
});
DEMO2
may be more correct is to spoof jQuery.fn.domManip like here
jQuery documentation:
Use of the .live() method is no longer recommended since later versions of jQuery offer better methods that do not have its drawbacks.
You can use setTimeout() function that can check for new <div>s every n milliseconds.
$(function(){
setInterval("Check4NewDivs();",1000);
});
So say this is a div with class="comment newdiv", so when it appears on the page for the first time, it has the class newdiv that will let the function know it was just dynamically created.
function Check4NewDivs(){
$(".comment .newdiv").each(function(){
$(this).append('<div class="new_feature"></div>').removeClass("newdiv");
});
}
It's append not appened.
live is a deprecated event handler. It's not used this way. use on instead.
http://api.jquery.com/live/
So, the following code will run when you click selector.
$(document).on('click', 'selector', function() {
$(this).append('<div id="new_feature></div>');
});
No, there is no standard way to do it like that. There was a proposal of the events that would be fired whenever the DOM elements are inserted etc., but you cannot rely on that.
Instead rely on either:
(preferably) callbacks - just invoke function ensuring existence of such appended snippets, whenever you pull something (but after you successfully pull it from server and insert into DOM, not sooner), or
constant checks - like using in setInterval() or setTimeout(), but this would be unnecessary processing and you will never get instant append, unless you will perform processing-heavy checks all the time,
use the on load function:
$(item).on('load',function(){
$(this).append('<div id="new_feature"></div>');
});
This will add append the item as a callback once the item has been loaded. I would also choose some sort of dynamic ID creator rather than always append stuff with the same ID, but thats just me.
you must bind to an element that already exists on the page. i have written an example where i make appended content live.
DEMO on JSFiddle
HTML
<div id="container">
<div id="features">
</div>
<br />
<a href='#' id='clickme'>click me to add feature</a>
</div>
JS
$(function() {
$('#clickme').on('click', function(e) {
$('#features').append('<div class="new_feature">new feature</div>');
});
$('#features').on('click', '.new_feature', function() {
alert('i am live.');
});
});

Basic jQuery Issues on IE9 (Toggle)

I'm not really a developper. I prefer to design my websites ... So, for my actual project, i must developping some "basic" scripts.
I've met a problem with this:
<script type="text/javascript">
$("button").click(function toggleDiv(divId) {
$("#"+divId).toggle();
});
;
</script>
Into Head-/Head
LINK
<div> id="myContent">Lorem Ipsum</div>
It works for IE8. (Miracle). But not the others browsers...
The idea is that when u click on "LINK" a windows appears and when you click again, the window close.
Any idea ?
Thanks for u time !
One of the problems is you're mixing two different styles of binding event handlers: one of them is good (the jQuery method), the other is bad (the javascript: protocol in your href attribute) - the two don't work together in any way. Another problem is that your selector is completely incorrect (it's looking for a button) for the HTML you've provided (you never create a button).
I'd suggest using a HTML5 data-* attribute to specify the id for the <div> on your <a> element:
LINK
<div id="mycontent">Lorem ipsum</div>
Then use the following jQuery code:
$('a').click(function(e) {
e.preventDefault(); // e refers to the event (the click),
// calling preventDefault() will stop you following the link
var divId = $(this).data('divid');
$('#' + divId).toggle();
});
Note that I've used this in the above code; what this refers to depends on the context in which you use it, but in the context of a jQuery event handler callback function, it will always refer to the element that triggered the event (in this case, your <a> element).
If you extract toggleDiv from the handler, it ought to work. You will probably also need to return false to keep the href from trying to go anywhere.
<script type="text/javascript">
function toggleDiv(divId) {
$("#"+divId).toggle();
return false;
}
</script>

Categories