Reputation:
I've created a jQuery hover function:
$('.deleteButton').hover(function(){
$(this).css('opacity', '1');
},
function(){
$(this).css('opacity', '.5');
});
It worked when I had the HTML element hard-coded into the index.html doc, but not when I import the element from a template.
Template below:
<div class="logBox">
<div class="dateAndLocation">
<p>{{ info.date | date }}</p>
<p style="margin-top:-.7em">{{ info.location }}</p>
</div>
<div class="routeNameBox">
<p class="routeName">{{ info.routeName }}</p>
<p class="gradeAndType">{{ info.grade }} | {{ info.type }}</p>
</div>
<div class="timeAndLevelBox">
<div class="timeBox pull-left">
<p class="timeText">{{ info.time }}</p>
</div>
<div class="pclBox pull-right">
<p class="pclText">{{ info.challengeLevel }}</p>
</div>
</div>
<div class="notesBox">
<p class="notesText">{{ info.notes }}</p>
</div>
<div class="photoCircle" style="background-image:url({{ info.photo }})"></div>
</div>
<div class="deleteButton"><p>—</p></div>
index.html code:
<div class="container" style="min-width:1200px; margin:auto;" ng-repeat="climbLog in climbLogs">
<climb-log info="climbLog"></climb-log>
<div>
It works fine and repeats as expected.. but when I hover over the delete button, it doesn't change it's opacity, as specified in the jQuery function (which had worked before I started using the template)
Upvotes: 1
Views: 1528
Reputation: 198344
The immediate problem is the fact that $(...).hover(...)
will only collect the nodes that exist right now, and attach a hover
handler on them. Thus, any future nodes that might eventually come to match the selector will not have the handler on them.
Using jQuery's on
(with live selector functionality) solves this issue: $('#placeWithDeleteButtons').on('hover', '.deleteButton', ...)
. This attaches the handler on the ancestor that catches the bubbled event, and checks if the triggering descendant matches the selector. Thus, since the handler is not on the trigger, you only need one handler to catch the event on any current or future matching nodes.
However, as comments indicate, you are better off using Angular's equivalents if you are working on an Angular project.
EDIT: Indeed, hover
has to be broken down to mouseenter
and mouseleave
:
$('.logBox').on("mouseenter mouseleave", ".deleteButton", function(evt) {
$(this).css('opacity', evt.type === 'mouseenter' ? 1 : 0.5);
});
.deleteButton {
opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="logBox">
<button class="deleteButton">Foo</button>
</div>
However, if all you want to do is change opacity on hover, there is a way easier way to do it:
.deleteButton {
opacity: 0.5;
}
.deleteButton:hover {
opacity: 1;
}
<div class="logBox">
<button class="deleteButton">Foo</button>
</div>
Upvotes: 2