Clicking on a flex card will trigger the opening of a new page where the parsed data will be displayed in a stylish manner using JavaScript

Currently, I am attempting to showcase the data retrieved from the following URL: . My objective is to format the parsed data with a specific style. However, I have encountered difficulties accomplishing this using `window.open()`. Any assistance in resolving this issue would be greatly appreciated.

<link rel="stylesheet" href="style.css">
<script type="text/javascript">
function clickFunction(recipes){    
    var myWindow = window.open("", "MsgWindow");
    //console.log(recipes);
    myWindow.document.write('<br>Name:'+recipes.name+'<br>');
    myWindow.document.write("<table><tr><th>Name</th><th>Amount</th></tr> 
    </table>");
    for(var i=0; i < recipes.Ingredients.length; i++){
        var name = recipes.Ingredients[i].name;
        var amount = recipes.Ingredients[i].amount;
        myWindow.document.write("<table><tr><td>"+name+"</td><td>"+amount+" 
         </td></tr></table>");
    }
    myWindow.document.write('<br>Steps:'+recipes.steps+'<br>');
    myWindow.document.write('<br>Similar Cuisines:'+recipes.SimilarCuisines+'<br>'); 
    myWindow.document.close();
   }
</script>
</head>

/* Rest of the HTML code as it is */

css:

*{
    box-sizing: border-box;
}
body{
    background: url('cutlery.jpg');  
}

/* Rest of the CSS code as it is */

js:

$(function(){
    var $container = $('.container');
    $.ajax({
        type:'GET',
        dataType: 'json',
        url:'https://s3-us-west-2.amazonaws.com/digicode-interview/Q1.json',
        success: function (data) {
            //console.log(data.recipes);
            var htmlContent="";
            for (var i=0; i<data.recipes.length;i++) {
                var recipe = data.recipes[i];

                htmlContent += "<div class=\"card\" onclick='clickFunction("+JSON.stringify(data.recipes[i])+")'>";
                htmlContent += "<h1>";
                htmlContent += data.recipes[i].name
                htmlContent += "</h1>";
                htmlContent += "</div>";
            }
            document.getElementById("recipebody").innerHTML = htmlContent; 
        }
    });
});

/* Rest of the JavaScript code as it is */

I am encountering challenges in properly formatting the content. While exploring various solutions, I have not been able to integrate them seamlessly into my current project.

Answer №1

When you decide to open a new window, keep in mind that the stylesheet will be lost. Therefore, ensure you write it in your document as shown below:

function clickFunction(recipes){  

    let myWindow = window.open("","Preview");
    
   
    myWindow.document.open();
     myWindow.document.write('<head>')
     myWindow.document.write('<link rel="stylesheet" href="yourstyle.css">');
          
     myWindow.document.write('</head><body>')

    myWindow.document.write('<br>Name:'+recipes.name+'<br>');
    myWindow.document.write("<table><tr><th>Name</th><th>Amount</th></tr> </table>");
    for(var i=0; i < recipes.Ingredients.length; i++){
        var name = recipes.Ingredients[i].name;
        var amount = recipes.Ingredients[i].amount;
        myWindow.document.write("<table><tr><td>"+name+"</td><td>"+amount+"</td></tr></table>");
    }
    myWindow.document.write('<br>Steps:'+recipes.steps+'<br>');
    myWindow.document.write('<br>Similar Cuisines:'+recipes.SimilarCuisines+'<br>'); 
         myWindow.document.write('</body>')

    myWindow.document.close();
   }


$(function(){
    var $container = $('.container');
    $.ajax({
        type:'GET',
        dataType: 'json',
        url:'https://s3-us-west-2.amazonaws.com/digicode-interview/Q1.json',
        success: function (data) {
            //console.log(data.recipes);
            var htmlContent="";
       //          htmlContent+='<head>';
     //htmlContent+='<link rel="stylesheet" href="style.css">';
          
     // htmlContent+='</head><body>';
            for (var i=0; i<data.recipes.length;i++) {
                var recipe = data.recipes[i];

  htmlContent += "<div class=\"card\" onclick='clickFunction("+JSON.stringify(data.recipes[i])+")'>";
                htmlContent += "<h1>";
                htmlContent += data.recipes[i].name
                htmlContent += "</h1>";
                htmlContent += "</div>";
            }
           //  htmlContent+='</body>'
            document.getElementById("recipebody").innerHTML = htmlContent; 
        }
    });
});
*{
    box-sizing: border-box;
}
body{
    background: url('cutlery.jpg');  
}
#root{
    max-width: 100%;
    margin: 0 auto;
    position: relative;
}

.container{
    display: flex;
    flex-wrap: wrap;  
    position: relative;
    padding:10px;
}
h1 {
    text-align: center;
    background-image: linear-gradient(120deg, #fbc2eb 0%, #a6c1ee 100%);
    font-size: 1.5rem;
    padding: 1rem 2rem;
    color: white;
}
.card {
    margin:5px;    
    background: white;
    box-shadow: 2px 4px 25px rgba(0, 0, 0, .1);
    border-radius: 12px;
    overflow: hidden;
    grid-gap:20px;
}
.card:hover {
    box-shadow: 2px 8px 45px rgba(0, 0, 0, .15);
    transform: translate3D(0, -2px, 0);
}
@media screen and (min-width: 600px) {
    .card{
        flex: 1 1 calc(50% - 2rem);
  }
}

@media screen and (min-width: 900px) {
    .card{
        flex: 1 1 calc(33% - 2rem);
  }
}
.card:nth-child(2n) h1 {
    background-image: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%);
}

.card:nth-child(4n) h1 {
    background-image: linear-gradient(120deg, #ff9a9e 0%, #fecfef 100%);
}

.card:nth-child(5n) h1 {
    background-image: linear-gradient(120deg, #ffc3a0 0%, #ffafbd 100%);
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">

</head>
<body>
<div id="root">
    <h1>List of Recipes</h1>
    <div class="container" id="recipebody">
    </div>
</div>

</body>

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

How can I notify an error in CoffeeScript/JavaScript when a parameter is not provided?

Initially, I believed that my code was clever for accomplishing this task: someFunction = (arg1, arg2, arg3) -> if _.some(arguments, (a) -> a is undefined) throw new Error "undefined parameter" My goal was to throw an error if any of the para ...

The <g> tag fails to properly render within the <svg> element in Firefox

When running an Angular 6 application with ES6-style D3js modules, there are some issues on Firefox (Chromium, Chrome, Safari, and IE Edge work fine). Below is a sample of pseudo code (full production code is available below): <svg width="500" height=" ...

I'm encountering CORS issues while attempting to log in using guacamole from my React app. Can anyone advise on what might be causing this problem

Having trouble logging into the Guacamole form through a React JS web application. The Guacamole server is hosted on Tomcat server, while the React app is on Node.js; both operating on separate domains. Despite using Nginx proxy on the server, encounteri ...

I'm looking for recommendations on the best method to develop reusable components using JavaScript and jQuery in an elegant way

I'm interested in finding user-friendly tools in JavaScript to easily create small, reusable components. I envision a component builder with a simple API that can generate HTML output for specified data, allowing for seamless embedding on websites. Co ...

Utilize/Absolve/Add a Prefix to angular material scss styles

Issue I am facing a challenge with integrating angular material SCSS into my application. I want to ensure that these styles are isolated and scoped specifically for my application, as it will be embedded within a larger monolith. The goal is to prevent a ...

Using regular expressions in Javascript to extract decimal numbers from a string for mathematical operations

I'm currently working on a Vue method where I extract information from a WordPress database. The data retrieved sometimes contains unnecessary text that I want to filter out. Using the prodInfo variable, the input data looks something like this: 2,5k ...

Exploring the implementation of window.addEventListener within an Angular project

I am currently working on testing a method in Angular using Jasmine. However, I am running into an issue with triggering the mouse event (specifically when the browser back button is clicked). Below is the code snippet I'm working with: navigate() { ...

Challenges with login pages integrating JS/JQuery and Firebase

I've been working on creating a login page where once the user successfully logs in, I want to make it so that they are redirected from the index.html page to my portfolio.html page. firebase.auth().onAuthStateChanged(user => { if(user) { wind ...

Which is better for SEO: using H tags or image alt text?

In need of a major website title that stands out. Which SEO solution reigns supreme? Implementing an image with alt text "my crucial page title" Utilizing h1 tags for the "my crucial page title" text ...

Parse the JSON data response as needed in ReactJS

var mydata = [ { source: 11, Registernumber: ">RT-113, <RT-333", jul1: 1004 }, { source: 11, Registernumber: ">RT-113, <RT-333", jul2: 1234 }, // Rest of the data entries... ]; Can we transform the above JSON ...

Success with AJAX, but Laravel is failing to insert data into the database

I am encountering a significant challenge with my upvote/downvote system. Despite the success of the AJAX execution, Laravel does not insert anything into the database. I am clueless about what could be going wrong. Here is my AJAX code: $('[data-val ...

Chrome's XPath attribute selection is not functioning properly

After running a small test with expect.js, here are the results: describe('xpath', function () { it('locates attribute nodes', function () { $(document.body).append('<string fooBar="bar"><data id="xyz">< ...

Using jQuery to retrieve the nth child from a table after dynamically creating it with AJAX

When using AJAX in the code below, I fill and create simple data after retrieving it. $.ajax({ method: 'GET', url: '/analyzePage/searchTag/' + tagName, contentType: false, processData: false, success: function (data ...

refresh polymer components or make an ajax request within a custom element

I've been spending days on this issue with no success! My application relies on cookies for session handling and includes multiple custom elements imported in the header. Some of these elements need to access information from the 'cookie session& ...

Finding out the specific row that was clicked in a Jquery Mobile listview

I've searched everywhere and can't find a solution. How can I retrieve the value of a row tapped in a listview? This could be anything from the name to the index within the object. Currently, I have a function handling the tap event. I need to pa ...

The properties of margin:auto and text-align:center are failing to function as expected

I'm facing an issue while creating a website. The 'margin: auto' and 'text-align: center' properties in my CSS code seem to not be functioning as expected. Can someone please review my code in inspect element and identify the probl ...

Guide to implementing a personalized filter in AngularJS 1.6

I am struggling with injecting a custom filter, status, into my component. Below is the code for my component: function ClaimsListController(dpClaimsListService) { var ctrl = this; ctrl.claims = null; ctrl.searchCriterion = null; ctrl.l ...

There seems to be an issue with accessing the / endpoint in node

index.js const path = require("path"); const express = require("express"); const exp = require("constants"); const dotenv = require("dotenv").config(); const port = process.env.PORT || 5001; const app = express(); //enable body parser app.use(express.jso ...

Track the cursor's movement

Looking to add an animation effect to my website. I want the navbar to follow the cursor within a limited space when hovered over. Check out this example for reference: . Here's the code I have so far, but it's not quite achieving the desired res ...

Trigger AngularJS directive on page load

I have a simple app where the user clicks a button on home.html to navigate to map.html. On map.html, a jQuery plugin (converted into a directive) should trigger when that view is loaded. Currently, it triggers immediately when the app loads (home.html), e ...