jQuery's ready function fails to trigger after using a rails link_to

I have implemented the following JavaScript code to create a "fade in" effect for an image triggered by a scroll event. However, the .hide function I am using to hide the image initially only works when the page loads at localhost:3000.

Once I navigate back to the main page by clicking on a link:

<%= link_to 'Main', root_path %>

The main page loads without the .hide functionality working as expected.

I'm puzzled why the .hide function works when the page initially loads but not when I navigate back to the same page. The rest of the JavaScript functions correctly - I can scroll and see the image fading in and out based on my scrolling position. However, I specifically require the image to start hidden, which only seems to work when the page is loaded initially. Any assistance would be greatly appreciated.

function isElementVisible(elementToBeChecked) {
    var TopView = $(window).scrollTop();
    var BotView = TopView + $(window).height();
    var TopElement = $(elementToBeChecked).offset().top + 100;
    var BotElement = TopElement + $(elementToBeChecked).height();
    return ((BotElement <= BotView) && (TopElement >= TopView));
}

$(document).ready(function(){
    $("#ghost_logo").hide();// hide it initially
});    

$(window).scroll(function(){
    isOnView = isElementVisible("#logoDiv");

    if (isOnView) {
        //fade out small image once main logo is in view
        $('#ghost_logo').fadeOut();
    } else {
        //fade in small image once main logo is out of view
        $('#ghost_logo').fadeIn();
    }        
});

Answer №1

If you're encountering a common issue with turbolinks, where the DOM doesn't update when navigating through links, there are a few solutions you can try.

One option is to add an event listener like this:

document.addEventListener('page:load', function(){
    $("#ghost_logo").hide();
});

If that doesn't work, you can attempt navigating without turbolinks by changing a parameter in the link:

<%= link_to 'Main', root_path ,{ :'data-no-turbolink' =>  "true" } %>

Alternatively, you may want to consider using the jQuery-turbolinks gem, which is designed to resolve these types of issues.

For further details, check out the turbolinks repository on GitHub.

Answer №2

document.addEventListener('page:load', function(){
    $("#ghost_logo").hide();
});

Doesn't seem to be effective at all times. Instead, try this:

document.addEventListener('turbolinks:load', function(){
    $("#ghost_logo").hide();
});

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

Error encountered when attempting to pass more than one value to a function due to syntax

My goal is to call a function, but I am encountering issues with properly escaping values and passing them correctly. The current setup looks like this: function selectdone(sel, title_id, status_type) { ... } $(function() { $("td.status-updates").click ...

A JavaScript tool that calculates the item price and total price

I am looking to create a trading calculator for a game and I believe a JavaScript calculator would be ideal as it can calculate on the fly. However, I have no idea where to begin. The goal is to determine the value of in-game items if they are traded for ...

Enabling asynchronous mode triggered an error, yet the data was still successfully transmitted to the server

When the Async setting is changed to true, an error message ("fail") is thrown as soon as the Ajax call is made. However, despite this error, the data is still sent to the server side and successfully saved. This behavior does not occur when Async is set t ...

unable to retrieve data from HTML element

Having trouble accessing the value inside an HTML tag? Here's my dilemma: I can grab the entire tag, but not the value inside. In my app.component.html file: <p #docTitle>the thing I want to extract</p> And in my app.component.ts file: ...

How can you conceal an HTML element when the user is using an iOS device?

I need the code to determine if a user is using an iOS device and, if not, hide the HTML input type "Play" button. So, I'm uncertain whether my iOS detection is correct, the hiding of the "Play" button in the code, or both: <!DOCTYPE html> < ...

changing up the format of nested blockquotes

My website includes various text features, which means that nested blockquotes are a possibility. I am now curious if it is feasible to style nested blockquotes differently from each other! blockquote{ background-color:#666; color:#fff; border ...

Diversifying brands in the realm of Angular 2/4

I am facing a scenario where I need to customize the styling of an Angular component in various ways. I am developing separate components such as buttons and lists for different brands that other developers can utilize on their websites. For instance, a si ...

The group of links is positioned beyond the bounds of the containing div

Check out this code snippet from <html> <head> <style type="text/css"> .wrapper1 { width: 65%; margin: 0px auto 0px auto; border: 1px solid; text-align: center; background: #eeeeee; } .wrapper2 { clear: left; ...

Establishing Node.js environment variables when invoking `npm run` command

package.json { "scripts": { "start": "NODE_ENV=development node ./index.js" } } If we wanted to pass and override NODE_ENV when running npm run start, is it possible? npm run start NODE_ENV=production ...

Difficulty in getting a response from WordPress AJAX Call

Being relatively new to WordPress and not having much experience with AJAX, I am currently in the process of setting up a simple AJAX call. While I believe I am close to getting it to work, I am facing an issue where I cannot retrieve any results from the ...

Leverage JSON data using props in React JS

Currently, my data is formatted in JSON and successfully populated into props known as foxFooterData. Upon inspecting the console.log result of foxFooterData.data, the following information is visible: https://i.sstatic.net/8htNG.png I am attempting to r ...

What is the reason for the malfunction of native one-time binding when using the `::` expression in Angular version 1.3.5?

I am having an issue with AngularJS's one-time binding feature using the :: expression. Despite my code setup, the values are still changing. I must be missing something crucial here. Consider this controller: $scope.name = "Some Name"; $scope.chang ...

Display a toolbar underneath text that has been selected using jQuery

I am attempting to display a toolbar underneath selected text once the user has made a selection. After exploring various Stack Overflow responses, I have devised the following code. My goal is for the toolbar to activate when a user selects text not only ...

Issues with JSON data retrieved via Ajax requests

Recently, I created a page on WordPress with the intention of submitting a form via AJAX. However, every time the form is submitted, the URL changes to the form handler's URL and instead of using the JSON data to update the current page, it simply dis ...

What steps can be taken to keep an SVG path (graphic) consistently centered, regardless of changes to the viewport?

My current project operates in 2 layers: the bottom layer features a large SVG object with numerous paths, while the top layer displays a small SVG object that I aim to keep perfectly centered. The bottom layer is positioned absolutely using CSS, and the t ...

Issues with the footer on Internet Explorer version 7

I am experiencing some challenges with certain footer elements in IE7. You can view the page I'm working on here. Firefox: IE7: Here is the code snippet: <div id="footer_container"> <div id="footer"> <div class="top_row"&g ...

Introduction to Monaca Onsen UI: A Step-by-Step Guide for

Searching for comprehensive walkthroughs on Monaca Onsen UI has proven to be a challenge. Many available tutorials are geared towards advanced users, making it difficult for beginners to follow along. The mix of Angular, jQuery, and plain JavaScript furthe ...

Ways to address Path Traversal vulnerability in the following code

const downloadFile = blobstoreRouter.get('/blobstore/download/:filename', (req, res) => { var localFile = path.join(__dirname, '..', escape(req.params.filename)); var file = require('fs').createWriteStream(localFile); try { ...

Create an iframe that spans the entire width of its containing element

I am struggling to make this iframe fill 100% of its parent div, which has a width of 900px. The current code is not achieving the desired result. Here is the HTML: <fieldset> <legend>Random Patch:</legend> <iframe src="../../ind ...

Step-by-step guide to uploading files with Dredd using Swagger

I am trying to send the following data in my api.description.yml: parameters: - name: "file" in: "formData" required: true type: file description: fileupload consumes: - multipart/form-data; I am not certain about the ...