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

Prevent incorrect data input by users - Enhancing JavaScript IP address validation

I have been trying to create a masked input field for entering IP addresses, but every solution I come across seems to have some flaws. The best solution I found so far is , but it still allows values higher than 255 to be entered. It works fine initially ...

Center an image vertically and horizontally within a div element inside a container, even if the image sizes and aspect ratio differ, while also including padding

I am looking to vertically align images with varying ratios, where the image may be larger or smaller than the content and also include padding; I have tried different solutions found here, but none seem to cover all my requirements; I specifically need i ...

Exploring various templates with AngularJS Directives

Let's delve into a slightly complex topic, but I'll simplify it as much as possible for you. There is a directive in play: .directive('configuratorRows', function () { return { restrict: 'A', scope: { ...

What is the best way to show the logged-in user's name with PHP?

After a successful login, I want to display a personalized greeting message to the user in PHP (e.g. "Hey User!"). However, the code $username = $_SESSION['username']; is not retrieving the username properly and displays nothing (Hey !). Here ...

When attempting to render HTML containing multiple CSS classes within a JSON request parameter, the styles are not being applied as expected

In my API, I'm dealing with a JSON request parameter that includes an HTML string. This HTML string references CSS styles from a separate .css file. However, when an HTML element has two CSS classes assigned to it, neither of the classes' styles ...

Load grid data only when the tab is clicked in ExtJS

Our app features a dynamic grid loaded with multiple tabs, each containing one or more grids. The issue currently is that when the application loads, it automatically calls all the URLs instead of waiting for the user to click on a tab. We want to optimi ...

Using jQuery to append content with a variable as the source

Recently delving into jQuery and encountering an issue with getting my variable inside src when using append. Either it's not functional at all, or just displaying the variable name in string form in the console. Here is the code causing trouble: va ...

Embed a javascript tag to print a PDF document

I have been struggling with printing a PDF file using JavaScript. I attempted to use the embed trick suggested in this Silent print a embedded PDF but unfortunately, the print function remained undefined. Then, I tried another approach using an Iframe and ...

Utilizing jQuery.ajax() to retrieve the child div from a separate page

Can anyone help me figure out how to use jQuery ajax() to load two children contents from an external page? I want a pre-loader to display before the main content loads. Below is the code snippet that I have tried. $.ajax({ url: 'notification.htm ...

Adding material-ui library to a stylesheet

Can I include @material-ui/core/colors/deepOrange in my CSS file? I want to import this library and use it as shown below: import deepOrange from '@material-ui/core/colors/deepOrange'; import deepPurple from '@material-ui/core/colors/deepPu ...

Guide to filling out select dropdowns in HTML with information from a database

I'm new to PHP and HTML, so please be patient with me. I've been attempting to populate a select box using data from a MySQL database, but all I see is an empty textbox. Here's my current code: <select name="cargo"> <?php ...

What is the best way to set the width of an element to 100% while accounting for padding

My dilemma involves an HTML input field. The input currently has padding: 5px 10px;, but I need it to occupy 100% of its parent div's width (which is fluid). If I try using width: 100%;, the input ends up being wider than intended due to the padding ...

Deleting a record by sending an HTTP request and then removing the corresponding object from an array in Vue.js

After successfully solving this particular issue with the help of @nils, I have encountered a new question that I hope someone can assist me with! My current situation involves having a list of records from which I can select and remove items with just on ...

Having trouble making `overflow: hidden` work correctly when using padding on an element with `height:

Looking for some coding help here. My aim is to create a customized select menu with a sleek animation effect. I initially decided to set the default height to 0 and use overflow: hidden, then switch it to auto when .active class is applied. But, I'm ...

Incorporating JavaScript and CSS files into a content page of a master page in ASP.NET: Steps to follow

I am facing an issue with adding javascript files and css to a content page of a master page in asp.net. I attempted to include a datetime picker on my ContentPage, but it only works on the masterpage. When I try to add the same code to my contentpage, i ...

Is it normal for a Firebase listener to trigger twice when adding date to the database in React?

I've developed a basic chat application. Once the user submits a message, it is stored in the database along with their username. this.ref.child("/chat").update({username: this.state.username, message: this.state.chatMessage}); Subsequently, I ...

Navigating horizontally within a list using Sencha Touch2

I currently have a list set up with the following configuration: var grid = Ext.create('Ext.List', { scrollable: { direction: 'horizontal', directionLock: true }, store: compStore, i ...

Listening for a click event on a newly added element using JQuery

I am relatively new to using JQuery and I have encountered an issue with adding a click event listener for a dynamically created button. When the user clicks on the first button, my function successfully adds a second button to a div. However, I am facing ...

"Encountering a Problem with Assigning Variables in Vue

My issue revolves around the integration of VueJs, Vue-Resource, and Laravel. The problem occurs when attempting to assign a local variable to response data received from an AJAX request using vue-resource. Code Javascript <script> flags_ ...

JavaScript code for Tree not functioning correctly on Internet Explorer

Seeking assistance to fix a bug in my JavaScript program. The code works perfectly on Google Chrome and Firefox, however it encounters an error in Internet Explorer 8 as indicated below. Any suggestions on how to resolve this issue would be greatly appreci ...