How to add laravel component in DOM using javascript - javascript

I am new on laravel framework.
I have created an component (lecture-content) having some files input options, and there is an button onclick which should add one more (lecture-content) component. On DOM.
function addContent()
{
let newDoc = "#include('inc.lecture-content')";
let extendContent = document.getElementById('addNew').innerHtml;
console.log(extendContent);
console.log(newDoc);
extendContent+=newDoc;
document.getElementById('addNew').innerHtml= extendContent;
}
<div class="cariculum-heading my-2">
<h5 class="my-auto py-auto font-weight-normal ">Curriculum </h5>
<button class="px-2 btn my-auto py-auto add-content-btn" onclick="addContent()" id="add-content">+ content</button>
</div>
<div class="content-section" id="addNew">
#include('inc.lecture-content')
</div>
but this is not working at this position let newDoc = "#include('inc.lecture-content')"; it shows syntax error. can anyone help me to resolve it. What I am doing wrong here

Use clone()
Below jQuery code will fulfill your purpose.
function addContent()
{
var clone = $('#addNew').clone().css('display','block');
$('#newEle').append(clone);
}
Add one more div to your blade file.
<div id="newEle">
</div>
This newly created div will be used to append cloned div.
function addContent()
{
var clone = $('#addNew').clone().css('display','block');
$('#newEle').append(clone);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cariculum-heading my-2">
<h5 class="my-auto py-auto font-weight-normal ">Curriculum </h5>
<button class="px-2 btn my-auto py-auto add-content-btn" onclick="addContent()" id="add-content">+ content</button>
</div>
<div id="newEle">
</div>
<div class="content-section" id="addNew" style="display: none;">
#include('inc.lecture-content')
</div>

Related

Creeating a div with an ID and then modify it

First of all, i'm a newb to HTML and JS and my english is not the best so sorry about that.
I have an id on a HTML element. I want to add content to this element with a function and create another element (inside the first one), with a new ID and then modify this last ID with a function that runs after the first one.
The id i have defined in HTML is "product-container"
With the function "show product()" i want to create its content and to create a div for its images (id=images-div), which i will add with the function "appendImages()".
I honestly don't know how to do this with only 1 function becouse the item has multiple images and i dont know how to iterate them in a for inside the innerHTML. But i think i should be able to do it this way.
I'm not sure if the problem is that i'm defining the variable (let imagesDiv = document.getElementById("images-div")) before the element is created...
HTML Code:
<div class="list-group" id="product-container"> </div>
JS Code:
const URL = PRODUCT_INFO_URL + localStorage.getItem("productID") + EXT_TYPE
let productContainer = document.getElementById("product-container")
let imagesDiv = document.getElementById("images-div")
let relatedProducts =document.getElementById("related-products")
let currentProduct = [];
function appendImages(){
let HTMLContentToAppend = "";
for (let productImage of product.images){
HTMLContentToAppend +=`
<div class="col-3">
<img src="${productImage}" alt="${product.name}" class="img-thumbnail">
</div>`
}
imagesDiv.innerHTML = HTMLContentToAppend
}
function showProduct(){
let product = currentProduct
productContainer.innerHTML = `
<div class="list-group-item">
<h1> ${product.name} </h1>
<hr>
<div class="col">
<div class="justify-content-between">
<h4 class="mb-1"> Precio </h4>
<p> ${product.currency} ${product.cost}
</div>
<div class="justify-content-between">
<h4 class="mb-1"> Descripción </h4>
<p> ${product.description}
</div>
<div class="justify-content-between">
<h4 class="mb-1"> Categoría </h4>
<p> ${product.category}
</div>
<div class="justify-content-between">
<h4 class="mb-1"> Cantidad de Vendidos </h4>
<p> ${product.soldCount}
</div>
<div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3" id="images-div">
</div>
</div>
</div>`;
appendImages()
};
Thanks in advance for the help and sorry for the newby question :/
What you assumed to be the problem is actually the problem. Move let imagesDiv = document.getElementById("images-div") inside the appendImages function.

How to add another HTML page to .innerHTML

Here's my code for a section of my page that i want to change
let existinguser = document.querySelector('#existing-user');
let table= document.querySelector('#table-contents');
existinguser.addEventListener('click', () => {
table.innerHTML = '';
});
since innerHTML only accepts string, how do i display content from another page
eg. new_page.html using .innerHTML
I dont't know if this will be required but here are the #existing-user snippets
<div class="col-xl-3 col-md-6">
<div class="card bg-primary text-white mb-4">
<div class="card-body">Existing User's requests</div>
<div class="card-footer d-flex align-items-center justify-content-between">
<a class="small text-white stretched-link" href="#" id="existing-user">View Details</a>
<div class="small text-white"><i class="fas fa-angle-right"></i></div>
</div>
</div>
</div>
You should use iframe for adding html pages
You can do hacky stuff. You can use Javascript to fetch another html.
fetch('new_page.html').then(res=>res.text()) and add the response to the innerHTML.
Use jQuery .load(url) or any other method of Ajax in general.
$(".container").load("https://jsonplaceholder.typicode.com/");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<h1>next content is loaded from another html page</h1>
<div class="container" style="background:#eee"></div>
<h1>previous content was loaded from another html page</h1>

TypeError: Cannot read properties of null (reading 'addEventListener') javascript

I am trying to add a button but it is showing me this error.
here is my html code
<div card-container>
<template class="mainTemplate">
<div class="cards">
<div class="card">
<img data-image src="" alt="">
<div data-title class="header"></div>
<div data-body class="body"></div>
<button data-button class="btn">read more</button>
<p data-paragraph class="fullText"></p>
</div>
</div>
</template>
</div>
here is the javascript code
let showDitail = document.querySelector(".btn");
showDitail.addEventListener("click", showMore);
function showMore(){
alert("e")
}
You're using the <template> tag, which is an element that holds html markup but it's not rendered on page load.
In order to render its contents, one has to handle the <template> element via javascript, using the html structure as - in fact - a template for filling another structure (a table, a divs grid, etc.).
Since the sub-elements of <template> are not part of the DOM yet, let showDitail = document.querySelector(".btn"); will result in null. That's why you cannot bind events to it.
Either change the tag to something else (a div maybe), or handle the template properly via javascript.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template
let showDitail = document.querySelector(".btn");
showDitail.addEventListener("click", showMore);
function showMore(){
alert("e")
}
<div card-container>
<div class="mainTemplate">
<div class="cards">
<div class="card">
<img data-image src="" alt="">
<div data-title class="header"></div>
<div data-body class="body"></div>
<button data-button class="btn">read more</button>
<p data-paragraph class="fullText"></p>
</div>
</div>
</div>
</div>

Find div before button

Im trying addClass to wizard-step when button clicked, but still no luck :/
<div class="mt-4">
<div class="wizard-steps">
<div class="wizard-step">
<div class="wizard-step-icon">
<i class="far fa-user"></i>
</div>
</div>
<form class="wizard-content mt-2" id="regForm">
<fieldset>
<div class="form-group row">
<div class="col-lg-4 col-md-6 text-right">
<button type="button" onclick="step0(this);" class="btn">Next</button>
</div>
</div>
</fieldset>
</form>
</div>
JavaScript:
<script>
function step0(element) {
$(element).prev('div').find('.wizard-step').addClass('wizard-step-active');
}
</script>
Can anyone please help me !
prev is used to retrieve a previous sibling element. The .wizard-step you want to target is a child of a sibling to a parent of the button being clicked. As such you need to use closest() instead.
Also note that onclick (and all the other onX attributes) are not good practice and should be avoided. As you're already using jQuery you can attach your event unobtrusively, like this:
jQuery($ => {
$('.btn').on('click', function() {
$(this).closest('.wizard-steps').find('.wizard-step').addClass('wizard-step-active');
});
});
.wizard-step-active { color: #C00; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mt-4">
<div class="wizard-steps">
<div class="wizard-step">
<div class="wizard-step-icon">
<i class="far fa-user">User icon</i>
</div>
</div>
<form class="wizard-content mt-2" id="regForm">
<fieldset>
<div class="form-group row">
<div class="col-lg-4 col-md-6 text-right">
<button type="button" class="btn">Next</button>
</div>
</div>
</fieldset>
</form>
</div>
Alternatively, instead of calling find() from the shared parent, you could select the form and use prev():
$('.btn').on('click', function() {
$(this).closest('.wizard-content').prev('.wizard-step').addClass('wizard-step-active');
});
Either is fine, it just depends on how your HTML is structured as to which fits best for this use case.
You don't want the div immediately before the button, but the one containing the relevant item(s). So instead of $(element).prev('div') write $('.mt-4').
Your this parameter is referring your button, not your div.
You can do this without Jquery, just using your function like this:
function step0() {
const element = document.getElementsByClassName('wizard-step');
element.classList.add('wizard-step-active');
}
So, you don't need to pass this as a parameter to step0 function.

Open Bootstrap modal clicking auto generated element

I've got a problem to open Bootstrap 4 modal using element generated by Javascript.
There are two very similar cards (identical but with diffrent id). First is hard coded in html doc (and work correctly). Another is generated by simple JS script. I try to use the same class name "openEditModal" but it doesn't work. Then I declared "data-toggle" "data-target" attributes for both but still work only hard coded card. Is there any possibility that Bootstrap JS file work only with hard coded element?
HTML Coded Card
<div class="row" id="all-contacts-box">
<!-- ____EXIST_ADDRESSES____ -->
<!-- addressBoxWrapper -->
<div class="col-xl-3 col-md-4 col-sm-6 col-12 mt-2 d-flex">
<!-- addressBox -->
<div class="card bg-light openEditModal label flex-fill">
<!--contactHeader-->
<div class="card-header pl-2 pt-1 font-weight-bold text-muted label-title">
Office Address
</div>
<!-- contactBody -->
<div class="card-body row pt-0">
<!-- contactBodyLeft -->
<div class="col-4 d-flex justify-content-center align-items-center maps-pin">
<i class="fas fa-map-marker-alt"></i>
</div>
<!-- contactBodyRight -->
<div class="col-8">
<h4 class="label-title font-weight-bold">Main Name</h4>
<h5 class="label-address font-weight-normal">Street 22</h5>
<h5 class="label-address font-weight-normal">City, Country</h5>
</div>
</div>
</div>
</div>
Part of JS Code that generate new card
var createContactBox = function(dataToDisplay, idCounter) {
var mainAddressContainer = document.getElementById("all-contacts-box");
var addNewBox = document.getElementById("add-new-box");
var addressBoxWrapper = document.createElement("div");
var addressBox = document.createElement("div");
mainAddressContainer.insertBefore(addressBoxWrapper, addNewBox);
addressBoxWrapper.appendChild(addressBox);
addressBoxWrapper.classList = "col-xl-3 col-md-4 col-sm-6 col-12 mt-2 d-
flex";
addressBox.classList = "card bg-light openEditModal label flex-fill";
addressBox.setAttribute("data-toggle", "modal");
addressBox.setAttribute("data-target", "editBoxModal");
};
$(".openEditModal").click(function() {
$("#editBoxModal").modal();
});
The problem with dynamically created elements, is that they aren’t born with the same event handlers as the existing elements.
In order to fix it, you need to "refresh" the listeners after you add a dynamically element.
So I add events handlers to a function and turn it off before I turn it on (something like restart). If you don't turn it off, the event will triggered as many times this function is called, and you don't want it.
function refreshEvents() {
$(".openEditModal").off();
$("#add-new-box").off();
$(".openEditModal").click(function() {
$("#editBoxModal").modal();
});
$("#add-new-box").click(function() {
$("#addNewBoxModal").modal();
});
}
Now you can call this function whenever you create another element.
So I call it after you created the element.
This is a working fiddle

Categories