Dude2019
Dude2019

Reputation: 95

How can I run a function on page load and then after click?

hi this is my very first time using jquery on any project at all. I am needing a little help if someone can

on my page i have some code to load a json file this file contains menu details for the main menu such as

name / action / poster

this is my code

var Items = "";
var flixAPI = "https://example.com/api.php?action=MAIN";

$.getJSON(flixAPI, function (data) {

    $.each(data, function (i, item) {
        Items += "<div class='img'>";
        Items += "<a target='_blank' href='" + item.ACTION + "'>";
        Items += "<img src='"+ item.POSTER +"' alt='" + item.NAME + "'>";
        Items += "</a>";
        Items += "<div class='desc'>" + item.NAME.substr(0, 16) + "</div>";
        Items += "</div>";
    });

    $('#content').html(Items);

});

i can get this code working when i place it into the document ready.

my issue is after the main menu is populated and added to the page i then need to stop the page redirecting when a href link is clicked and get the value of the href link to then send another get json request to load the next page

i have tried loading the main menu on the document ready and then sticking one call into a .click binding to load the next set of items based on the href link clicked but when i try do this inside or outside the document ready the .click binded function wont work

Upvotes: 0

Views: 739

Answers (2)

Barmar
Barmar

Reputation: 780724

Put the code in a named function so you can call it from both places.

function getFlix(flixAPI) {
  var Items = "";

  $.getJSON(flixAPI, function(data) {
    $.each(data, function(i, item) {
      Items += "<div class='img'>";
      Items += "<a class='menu-link' target='_blank' href='" + item.ACTION + "'>";
      Items += "<img src='" + item.POSTER + "' alt='" + item.NAME + "'>";
      Items += "</a>";
      Items += "<div class='desc'>" + item.NAME.substr(0, 16) + "</div>";
      Items += "</div>";
    });
    $('#content').html(Items);
  });
}

$(document).ready(function() {
  getFlix("https://example.com/api.php?action=MAIN");
  $("#content").on("click", ".menu-link", function(e) {
    e.preventDefault();
    getFlix(this.href);
  });
});

This uses event delegation because the menu links are added dynamically. See Event binding on dynamically created elements?

Upvotes: 2

Sameer
Sameer

Reputation: 383

You would need to identify the menu items with either classes or id's.

Then you would have to define the onClick event for each one of those who you need to fetch the JSON for.

ON the onClick event, you need to use e.stoppropagation or e.preventdefault (check the usage online) and then use ajax to fetch the JSON and populate whatever you are populating.

Upvotes: -1

Related Questions