Switching from hover to onload事件 in the JavaScript code

I am currently modifying some preexisting code to suit my requirements.

https://tympanus.net/codrops/2010/02/08/awesome-css3-jquery-slide-out-button/

The sliding effect of the content when hovered with the mouse is what I am looking for. It seems straightforward, but I want it to activate automatically, without any user interaction.

Let's say it begins in a closed state, then opens after 2 seconds. It remains open for 5 seconds and then closes again, all without requiring mouse input.

<script type="text/javascript">
    $(function() {
        $('.slidebttn').hover(
            function open() {
                var $this       = $(this);
                var $slidelem   = $this.prev();
                $slidelem.stop().animate({'width':'225px'},800);
                $slidelem.find('span').stop(true,true).fadeIn();
                $this.addClass('button_c');
            },
            function close() {
                var $this       = $(this);
                var $slidelem   = $this.prev();
                $slidelem.stop().animate({'width':'70px'},700);
                $slidelem.find('span').stop(true,true).fadeOut();
                $this.removeClass('button_c');
            }
        );
    });
</script>

Any suggestions on what adjustments I should make to achieve my objective?

JSFiddle: https://jsfiddle.net/mj7yumfw/14/

Answer №1

Check out this version:

<script type="text/javascript>
$(function() {
    setTimeout(initSlider, 2000);
});
function initSlider() {
    openSlider();
    setTimeout(closeSlider, 5000);
}
function openSlider() {
    var $button       = $('.slidebttn');
    var $slider       = $button.prev();
    $slider.stop().animate({'width':'225px'},800);
    $slider.find('span').stop(true,true).fadeIn();
    $button.addClass('button_c');
}
function closeSlider() {
    var $button       = $('.slidebttn');
    var $slider       = $button.prev();
    $slider.stop().animate({'width':'70px'},700);
    $slider.find('span').stop(true,true).fadeOut();
    $button.removeClass('button_c');
}
</script>

The unique aspect of this script is the use of timeouts to control the slider initialization and closing functions. This separation allows for flexibility in when these functions are triggered.

You have the ability to adjust the timing of the slider opening and closing. Currently, the opening time is set to 2000 (approximately 2 seconds) and the closing time is set to 5000 (approximately 5 seconds).

Keep in mind that this script will only work if the buttons are present, as the sliding element is identified using the .slidebttn class.

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

What are effective ways to eliminate cross-origin request restrictions in Chrome?

Just starting out with angular and trying to incorporate a templateUrl in an angular directive. However, when attempting to view the local html file in the browser, I encounter the following errors --> XMLHttpRequest cannot load file:///Users/suparnade ...

The functionality of React-router-dom protected routes seems to be malfunctioning

Understanding Protected Routes in React.js: While looking at the implementation of protected routes, you may notice that 'false' is being directly used in the if statement. However, even with this condition, the page is still accessible. Why doe ...

When using React, the event.target method may unexpectedly return the innerText of a previously clicked element instead of the intended element that was

I have implemented a drop-down menu that triggers an event handler to return the selected option when it is clicked. Upon clicking on an option, I retrieve the inner text of that option using the event. The code snippet looks like this: event.target.inner ...

The interfaces being used in the Redux store reducers are not properly implemented

My Redux store has been set up with 2 distinct "Slice" components. The first one is the appSlice: appSlice.ts import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import type { RootState } from "./store"; export interface CounterState { value ...

Bootstrap 5.5.2 facing transition issues on bundle.js

Recently, I attempted to incorporate zoom.js into my project to enable image zoom functionality similar to that of the medium website. After linking both the CSS and JS files, it seemed to be working properly. However, I encountered an issue where the tra ...

Can you assist me with setting a value in an ASP dropdownlist?

I have an asp dropdownlist and I need to set its value from the client side. Although I am able to retrieve the data from the client side, I am facing difficulty in setting it in my asp dropdownlist using JavaScript. HTML <div class="col-md-6 form-gro ...

A React component utilizing dangerouslySetInnerHTML and including CSS styles

One of my React components displays the following element: <div dangerouslySetInnerHTML={{__html: this.props.htmlString}}/> While the html renders correctly, I am facing a challenge with my client-side CSS code affecting the component I am renderin ...

Despite making changes, the React Element continues to be rendered

I am a beginner in React and facing an issue with my simple app My aim is to implement a search functionality, but the problem arises when I search for an element - all search results are displayed After clearing the search box, all elements appear as in ...

Changes are not being detected in new Angular 2 files

Currently, I am enhancing an Angular 2 project by incorporating new modules. However, the changes I made in these files are not being recognized within the project. I have attempted to research how change detection functions in Angular 2, but have not bee ...

Creating Styles in Material-UI using makeStyles: Tips for Styling by Element Name

I am currently facing a challenge of adding a rule for all <p> tags within the current component. Despite searching through various sources such as material-ui documentation and Stack Overflow, I have been unable to find any information on how to add ...

Connect the attributes of one object to the properties of another object

I am looking to create a new object in Javascript and assign its property some values from another object. I want this assignment to be like 'pass by reference' in C++. In the code snippet below: var object1 = { 'obj1' : { &ap ...

Encountering 'Element not found' error when automating Flight Booking on MakeMyTrip.com using Selenium WebDriver, specifically while trying to select a flight after conducting a search

Currently in the process of automating the flight booking feature on MakeMyTrip.com using Selenium WebDriver. I have implemented separate classes for Page Object Model (POM) and TestNG. The code successfully automates the process up to the point of clicki ...

The ViewChild instance is currently undefined

Within my component, I have the following setup: @ViewChild('PaginatedTableComponent') userTable: PaginatedTableComponent; Here is the corresponding HTML code inside the component: <pag-paginated-table #userTable [(shouldUpdate)]="sh ...

Methods for submitting POST requests with key data enclosed in quotation marks?

Upon investigation, I discovered that the Request Payload object's key does not have quotation marks as shown below. https://i.sstatic.net/U54V9.png However, I am interested in sending a request with keys that are marked with quotations. Interestingl ...

Looping through an array of JSON objects in Javascript results in finding instances, however, the process records them

Currently, I am executing a script inside a Pug template. The script commences by fetching an array of JSON objects from MongoDB. I then stringify the array (data) and proceed to loop through it in order to access each individual JSON object (doc). Subsequ ...

Access a different tab through the utilization of JavaScript functions

Hi everyone, I recently created tabs using bootstrap, but I am facing a challenge with a specific scenario. I need the active tab to switch to another tab when a submit button is clicked. <div id="checkout-progress"> <ul class="nav nav-tabs"& ...

Ways to retrieve the resolved value from a promise beyond its initial scope

Having trouble passing the value outside the scope after resolving the promise. Can you take a look at my code below? var FullName; async.series([ function(callback) { var name = element(by.css('.xyz')).getText().then(function(text) { ...

Creating a webpage with a feature that allows users to click a button and instantly change the background to a

Here is the code I have for generating random colors: const colors = ["green", "red", "rgba(133,122,200)", "#f15025"]; const btn = document.getElementById('btn'); const color = document.querySelector('.color'); btn.addEventListener(&a ...

What is the best way to fetch all the orders from my product schema using response.send?

This is my custom Product schema const productSchema = new mongoose.Schema({ title: { type: String, required: [true, "Title is required"] }, details: { type: String, required: [true, "Details are r ...

Error: scrollreveal JavaScript is not properly defined

Desperately seeking guidance on a particular code snippet... window.sr = ScrollReveal({ reset: true }); sr.reveal('.whitecircle, .circleStatsItemBox, .circleStat', { duration: 200 }); function circle_program() { var divElement = $(&apo ...