rackymortor rackymortor - 3 months ago 18
CoffeeScript Question

Multiple conditions with jquery?

Using coffeescript, I want to be able to change my search icon to completely opaque when I hover over it. But only when the search input field is not in focus. When in focus, I don't wan't the hover to have any affect at all. So I have a custom class in css that I only want to trigger when both of these events are true. Something like:

if $(".search input")is(":hover") && !$(".search input")is(":focus")

where that custom .iconhover class in css would be

.iconhover {
opacity: 1;

But that doesn't seem to work for me. Is there anyway to combine the conditions in a way where hovering over the search icon only makes it opaque when the input is not in focus?

The HTML page:

<ul class="nav">
<li><%= link_to "home" %></li>
<li><%= link_to "about" %></li>
<li><%= link_to "help" %></li>
<li><%= link_to "tags" %></li>
<li class="searchbox">
<div class="input-wrapper">
<%= form_with(model: @something, class: "search") do |form| %>
<%= form.text_field :search %>
<% end %>

<a href="#"><i class="regular-icon"></i><a>

my coffeescript:

$(document).on "ready page:load", ->
$(document).scroll ->
scroll_start = 0
scroll_start = $(this).scrollTop()
if scroll_start > 575

if $(".search input")is(":hover") && !$(".search input")is(":focus")

and the related css is:

.iconhover {
opacity: 1;
} //which is the class I want to change to

.regular-icon {
color: black;
opacity: 0.4;
} //the current styling of the icon

Answer Source

I don't do Coffeescript, so my answer is in plain Javascript, you'll have to translate it.

To run code when the user hovers over an element, use the .hover() method.

You'll also need a .focus() handler, so you remove the class when the user focuses on the input, since .hover() only runs when the user enters or leaves, not when state changes while they're already hovered.

$(".search input").hover(function() {
    $(".regular-icon").toggleClass("iconhover", !$(this).is(":focus"));
  function() {
  }).focus(function() {
.regular-icon.iconhover {
  background-color: pink;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="search">
<div class="regular-icon">Icon</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download