Disable a jQuery function when another one is triggered

My webpage features a search function with some working code in place.

search.click(function () {
    search.attr("src", "Icons/magnifier.png").css({
        "border": "2px",
        "border-style": "solid",
        "border-color": "#000000",
        "padding-left": "130px",
        "transition": "all 500ms"
    });
});
$('html').click(function (e) {
    if (e.target.id != 'search') {
        $("#search").attr("src", "Icons/magnifier2.png");
        $("#search").css({
            "border": "2px",
            "border-style": "solid",
            "border-color": "#c8c8c8",
            "padding-left": "4px",
            "transition": "all 500ms"
        });
    }
});

The current functionality changes the icon and expands the border to the left when clicked, which reverts back to normal when the user clicks anywhere else on the page.

Now, I want to implement a hover effect that highlights the search button.

I have the following code:

 var search = $("#search");
 search.mouseover(function (event) {
     search.css({
         "border": "2px",
         "border-style": "solid",
         "border-color": "#808080",
         "padding-left": "4px",
         "transition": "all 500ms"
     });
 });

 search.mouseout(function (event) {
     if (event != ('clicked')) {
         search.css({
             "border": "2px",
             "border-style": "solid",
             "border-color": "#c8c8c8",
             "padding-left": "4px",
             "transition": "all 500ms"
         });
     }
 });

The hover effect works as intended, but when I click on the button and move my mouse away, the mouseout function triggers. I attempted a conditional statement to prevent this behavior, but I know it's incorrect. The hover function should not be active when the border is expanded. How can I address this issue?

If you could provide an explanation along with the solution, I would greatly appreciate it as I am new and trying to learn more about these concepts.

https://jsfiddle.net/g2aLwLhg/

Answer №1

To achieve the desired effect, it is advisable to separate CSS and JavaScript concerns for better organization. Below is a refined example illustrating how this can be done:

HTML

<div class="hoverStyles">Hover Here!</div>
<button onclick="toggleHover()">Toggle hover</button>

CSS

.hoverStyles {
  background-color: blue;
  color: white;
}

.hoverStyles:hover {
  background-color: yellow;
  color: blue
}

.noHoverStyles {
  background-color: blue;
  color: yellow;
}

JavaScript

function toggleHover() {
  if ($('.hoverStyles').length > 0) {
    $('.hoverStyles').addClass('noHoverStyles').removeClass('hoverStyles');
  } else {
    $('.noHoverStyles').removeClass('noHoverStyles').addClass('hoverStyles');
  }
}

[Update] Please note that the code snippet below has been revised for accuracy (refer to comments). Kindly refer to the provided link for verification.

Click here for a live demo.

If you require further assistance, feel free to reach out!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problem with CSS3 Target Selector

As I delve into the world of JS/HTML5/CSS3, I have been immersing myself in code examples from three different authors and combining and modifying them to enhance my learning. You can find my work-in-progress Pen, with references to the original authors, r ...

No acknowledgment from command

Why doesn't the bot respond when I run this command? There are no errors. Do I have the role that matches in r.id? client.on('message', async message => { // Check if the user has a role with an id if(message.author.bot) return; ...

Cordova: displaying websites in a webview

When loading an external website with different HTML files in an iframe within a Cordova webview on iOS, I encountered an issue. Whenever I click on a link within the iframe that points to another HTML page, it opens in the Safari browser instead of changi ...

Adjust the Scope in Angular-Charts.js Post-Rendering

I am currently facing a challenge with displaying multiple charts using the angular-charts.js framework. The issue is that I require all the charts to have the same scale, but each chart currently has its own scale based on the displayed data. Unfortunatel ...

Explore the possibilities of using a unique custom theme with next.js, less, and ant design

Trying to customize the default theme in antdesign has been a challenge for me. I've switched from sass to less, but there seems to be something that just won't work. I've exhaustively searched online for solutions - from official nextjs ex ...

Manipulating HTML content with Javascript Array

Is there a way to retain Javascript context from an array? Any suggestions for improving this code? SAMPLE: <html> <script type="text/javascript"> var rand = Math.floor(Math.random() * 6) + 1; var i = Math.floor(Math.random() * 6) + 1; var ...

Ways to access the state of a child component in React using React Hooks

What is the most effective solution for accessing a child's state in React using hooks? I have experimented with multiple methods, and below is the one I ultimately settled on. Parent Form export const Form: FunctionComponent<IProps> = ({ on ...

Retrieve the unique identifier of a single post from a JSON file within a NuxtJS project

Is there a way to retrieve the unique post id data from a JSON file in NuxtJS? created() { this.fetchProductData() }, methods: { fetchProductData() { const vueInstance = this this.$axios .get(`/json/products.json`) ...

Error: The bun.js application encountered a SegmentationFault at line 188

I'm attempting to execute the following command on my current repository, which already has a registry set up in the .npmrc. bun install -y The purpose of the -y flag is to generate the yarn v1 lockfile. However, it's resulting in the followin ...

Combining NodeJS and ExpressJS to deliver a unified JavaScript file when in production mode

Currently, I am managing multiple individual JS files in the following way: <script defer src="/js/libs/jquery.min.js"></script> <script defer src="/js/libs/plugins.js"></script> <!-- application core --> <script defer sr ...

Monitor Socket IO for client disconnection events

I am facing an issue where I need to identify when a user loses connection to the socket. It seems that socket.on("disconnect") is not triggering when I simply close my laptop, leading to the ajax call not executing to update the database and mark the us ...

FireFox - Dynamic Blinking Divs on Hover

It seems like in FireFox and IE, my hover effect is blinking for some reason. I can't figure out why this is happening. Should I switch to using JavaScript for my hovers or is there an easier CSS solution? Here's a JSFiddle link to demonstrate th ...

Eliminating the need for RequireJS in the Typescript Visual Studio project template

After integrating RequireJS into my Typescript template using the nuget package manager, I found that it was more than what I needed and decided to uninstall it. Even though I removed the package through nuget and the files were deleted properly, my Typesc ...

Transform preexisting Vue UI library measurements into pixels

I was curious about converting all existing units (em / rem) to pixels. How can I easily convert the entire output units to px? Are there any tricks or methods available? Currently, I am utilizing Vuesax UI to create a plugin for various websites and temp ...

Tips for preventing the appearance of a horizontal scroll bar when utilizing the FlexLayoutModule in Angular

import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-property-feed', templateUrl: './property-feed.component.html', styleUrls: ['./property-feed.component.scss'] }) export class Prope ...

`How can I activate caching for getServerSideProps in Next.js?`

We have implemented server-side rendering for a few pages and components. In an attempt to optimize performance, we have been experimenting with caching API responses. export async function getServerSideProps(context) { const res = await getRequest(API ...

Outlook.com eliminates placeholder links within emails

In my HTML email template, I have included an anchor tag with the href attribute set to a handlebars.js variable. Here is an example: <td class="body-text" align="left" class="padding">For the latest information on this order, please <a href="{{ ...

Problem with JQuery Dialog Box and Div

Within my HTML I have a div labeled "passage-content". This div's text is meant to be displayed in a jQuery dialog box when a button is clicked, however the content of the div is constantly changing due to the dynamic nature of the page. Each time the ...

"Upon refresh, the overflow property of the child element is being applied to the window position

In the React app I'm working on, there's a search results page where users can apply filters. These filter selections update the query params in the URL and trigger a re-mount in React. However, I've encountered an issue across different bro ...

Unlock the full potential of the PanelSnap plugin in your angular2 project with these easy steps

I had been successfully using the jquery.Panelsnap plugin on my static HTML pages. However, as I am now transitioning my application to angular8, I am encountering difficulties in referencing the PanelSnap plugin. npm install panelsnap Within my app. ...