Jquery change data-src of an parent image - javascript

I have following html structor the content is added dynamically
<div class="media text-muted pt-3">
<img data-src="holder.js/32x32?theme=thumb&bg=d32f2f&fg=d32f2f&size=1" alt="todo" class="mr-2 rounded">
<div class="media-body pb-3 mb-0 small lh-125 border-bottom border-gray">
<div class="d-flex justify-content-between align-items-center w-100">
<strong class="text-gray-dark">{{ $ticketValue->title }}</strong>
</div>
<br>
<div class="d-flex justify-content-between align-items-center w-100">
<span class="d-block">
<strong>Erstellt von {{ $ticketValue->description }}</strong>
</span>
<button type="button" class="closing-ticket" data-ticket-id="{{ $ticketValue->id }}">
<i class="fas fa-check"></i>
</button>
</div>
</div>
</div>
If the user click on the button I would like to change the data-src of the current parent image tag.
So far I have done this:
this.closingTicket.click((e) => {
let _this = $(e.currentTarget);
axios.post('ticket/close/' + this.elements.closingTicket.attr('data-ticket-id'))
.then((response) => {
_this.hide(); // hides buttons
// trying to find the image and change its data-src
_this.parent().parent().parent().find('img').data('src', 'holder.js/32x32?theme=thumb&bg=64dd17&fg=64dd17&size=1');
})
.catch((error) => {
// error
})
});

Related

How to update JavaScript after executing a function?

Good day to all, I'm new to js, so I would like to ask you, after executing the function, I add a response with content via innerHTML, but this content should also work with javascript, but it works, so I have to restart the page, how to do it right so that my functions work with the added answer?
Need to run this code
document.querySelectorAll('.btn-comment-like, .btn-comment-dislike').forEach((e) =>
e.addEventListener('click', function(e) {
e.preventDefault()
const commentRatingButtons = this;
const commentRatingId = commentRatingButtons.getAttribute('data-id');
const commentRatingAction = commentRatingButtons.getAttribute('data-action');
const commentTotalRating = document.querySelector(`button[data-comment-rating='${commentRatingId}']`);
const commentMessageRating = document.querySelector(`div[data-comment-message='${commentRatingId}']`);
fetch(`/api/comments/${commentRatingId}/${commentRatingAction}/`, {
method: 'POST',
headers: {
"X-CSRFToken": csrftoken,
"X-Requested-With": "XMLHttpRequest",
},
}).then((response) => response.json()).then((result) => {
if (result['error']) {
commentMessageRating.innerHTML = `
<div class="alert alert-danger rounded-0 shadow-sm me-2 align-self-start mb-2" role="alert" style="padding:2px;">
<i class="fa-solid fa-hexagon-exclamation"></i> ${result['error']}!
</div>`
} else {
if (commentRatingAction === 'like') {
commentMessageRating.innerHTML = `
<div class="alert alert-success rounded-0 shadow-sm me-2 align-self-start mb-2" role="alert" style="padding:2px;">
<i class="fa-solid fa-face-smile"></i> Спасибо за оценку, ${result['author']}!
</div>`
} else {
commentMessageRating.innerHTML = `
<div class="alert alert-danger rounded-0 shadow-sm me-2 align-self-start mb-2" role="alert" style="padding:2px;">
<i class="fa-solid fa-face-frown"></i> Спасибо за критику, ${result['author']}!
</div>`
}
commentTotalRating.innerHTML = `${result['comment_total_rating']} <i class="fa-solid fa-hand-holding-heart"></i>`
}
})
})
)
after doing this
commentForm.addEventListener('submit', function(e) {
e.preventDefault()
const commentForm = this;
const commentFormSubmit = commentForm.querySelector('#commentSubmit');
const commentArticleId = commentForm.getAttribute('data-article-id');
const commentEmpty = document.querySelector('#emptyComments');
const commentNestedList = document.querySelector('.nested-comments');
commentFormSubmit.innerText = "Ожидаем добавления...";
commentFormSubmit.disabled = true;
fetch(`/api/articles/${commentArticleId}/comments/create/`, {
method: 'POST',
headers: {
"X-CSRFToken": csrftoken,
"X-Requested-With": "XMLHttpRequest",
},
body: new FormData(commentForm),
}).then((response => response.json()))
.then((result) => {
if (result['comment_is_child']) {
const commentParentThread = document.querySelector(`#comment-thread-${result['comment_parent_id']}`);
commentParentThread.innerHTML += `
<ul id="comment-thread-${result['comment_id']}">
<li>
<div class="card mb-3 nth-shadow border-0 rounded-1">
<div class="card-body">
<div class="row">
<div class="col-md-2 d-none d-sm-inline pe-0">
<img src="${result['comment_avatar']}" class="img-fluid rounded-1 nth-img-comment nth-shadow" alt="{{ node.author.username }}">
</div>
<div class="col-md-10">
<div class="d-flex flex-row gap-2">
<div class="card-title">
<h6 class="nth-card-user-username mb-0">${result['comment_author']}</h6>
</div>
<div class="nth-card-title-username">
${result['comment_created_at']}
</div>
</div>
<div class="card-text mb-2">
${result['comment_content']}
</div>
<div class="d-grid gap-2 d-md-block">
<button class="btn btn-outline-secondary nth-btn-sm btn-like shadow-none" data-id="${result['comment_id']}" data-action="like" type="button">+1 <i class="fa-solid fa-heart-circle-plus"></i></button>
<button class="btn btn-outline-secondary nth-btn-sm btn-dislike shadow-none" data-id="${result['comment_id']}" data-action="dislike" type="button">-1 <i class="fa-solid fa-heart-circle-minus"></i></button>
<button class="btn btn-outline-secondary nth-btn-sm shadow-none" type="button" data-comment-rating="${result['comment_id']}">${result['comment_total_rating']} <i class="fa-solid fa-hand-holding-heart"></i></button>
</div>
</div>
</div>
</div>
</div>
</li>
</ul>
`
} else {
if (commentEmpty) {
commentEmpty.remove();
}
commentNestedList.innerHTML += `
<ul id="comment-thread-${result['comment_id']}">
<li>
<div class="card mb-3 nth-shadow border-0 rounded-1">
<div class="card-body">
<div class="row">
<div class="col-md-2 d-none d-sm-inline pe-0">
<img src="${result['comment_avatar']}" class="img-fluid rounded-1 nth-img-comment nth-shadow" alt="{{ node.author.username }}">
</div>
<div class="col-md-10">
<div class="d-flex flex-row gap-2">
<div class="card-title">
<h6 class="nth-card-user-username mb-0">${result['comment_author']}</h6>
</div>
<div class="nth-card-title-username">
${result['comment_created_at']}
</div>
</div>
<div class="card-text mb-2">
${result['comment_content']}
</div>
<div class="d-grid gap-2 d-md-block">
<button class="btn btn-outline-secondary nth-btn-sm btn-comment-like shadow-none" data-id="${result['comment_id']}" data-action="like" type="button">+1 <i class="fa-solid fa-heart-circle-plus"></i></button>
<button class="btn btn-outline-secondary nth-btn-sm btn-comment-dislike shadow-none" data-id="${result['comment_id']}" data-action="dislike" type="button">-1 <i class="fa-solid fa-heart-circle-minus"></i></button>
<button class="btn btn-outline-secondary nth-btn-sm shadow-none" type="button" data-comment-rating="${result['comment_id']}">${result['comment_total_rating']} <i class="fa-solid fa-hand-holding-heart"></i></button>
</div>
</div>
</div>
</div>
</div>
</li>
</ul>
`
}
commentForm.reset();
commentFormSubmit.innerText = "Добавить комментарий";
commentFormSubmit.disabled = false;
commentFormParentField.value = null;
})
})
I would be very grateful if you direct me to the correctness of creating such methods.
If you are feeling lazy to add it to the function then do something like:
let href = "http://"; //the location of your own html file you are working on.
//This will open your file on a new tab
window.open(href, "_blank");
//This will close your own tab.
window.close();
In this way you can close and open the tab again if it does'nt work with: "window.location.reload".
Put all your js code that you want to reload in a function and simply call it again when you want to. You can also use: window.location.reload();

Showing a button that pushes all other elements to the side (CSS Transition)

Basically, I'm having cards that have a height set by the flex behaviour. I'd like to add a button from the side that is only shown when the card is hovered so the button would come out from the right side of the container with a transition and start expanding and pushing all other content to the left until it finishes expanding. Therefore, I've looked for hours and I tried many things out and I couldn't find a solution. Could someone please help me out on this? here is my code, I'm using Bootstrap 5. Here is the UI I created
Here is my code . I'm using VueJS and my data is coming from an API.
<template>
<div class="d-flex col-12 flex-column bd-highlight mb-3">
<div class=" d-flex border border-dark col-12 flex-column" v-for="(question,index) in questions" :key="question + index">
<div class="d-flex col-12 justify-content-between">
<div>
<span class="text-wrap text-break">{{question.description}}</span>
</div>
<div class="d-flex">
<span :class="question.complexity.toLowerCase() === 'easy' ? 'badge bg-success align-self-start' : question.complexity.toLowerCase() === 'medium' ? 'badge bg-warning align-self-start' : 'badge bg-danger align-self-start' ">{{question.complexity}}</span>
</div>
</div>
<div class="d-flex flex-wrap">
<div class="p-2" v-for="(tag,index1) in question.tags" :key ="tag + index1">
<span class="badge bg-dark text-white"><i :class="'devicon-'+tag.nom.toLowerCase()+'-plain'"></i> {{tag.nom}}</span>
</div>
<div class="align-items-center d-flex w-100 justify-content-end">
<span>
<i class="fas fa-stopwatch"></i> {{question.duree}} secs </span></div>
</div>
</div>
</div>
</template>
Here is my UI
Expected Result ( Buttons should be with the same size )

Apply different styles to bootstrap card

I'm working with Angular 9 with a Bootstrap 4 card applying NGFOR to paint as many elements as come from the database.
I have the following array with different styles for that card and I would like them to be applied to each one in a random way.
public color_border = ["border-left-warning", "border-left-info", "border-left-primary"]
The card code is as follows: the div card border-left-info has to be changed. I have tried a new NGFOR but it duplicates everything.
<!-- Pending Requests Card Example -->
<div class="col-xl-3 col-md-6 mb-4" *ngFor="let data of miDataInterior.DatagreenhouseRecuperado; let i = index">
<div class="card border-left-info shadow h-100 py-2">
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-warning text-uppercase mb-1">{{data.medidas[0].sensor_type[0].name_comun}}</div>
<font SIZE=3> {{data.medidas[0].marca}} </font>
<font SIZE=3>({{data.medidas[0].recvTime | date:'dd-MM-yy h:mm:ss a'}})</font>
<div class="h5 mb-0 font-weight-bold text-gray-800">{{data.medidas[0].attrValue | number:'1.0-1'}} {{data.medidas[0].sensor_type[0].medida}}</div>
</div>
<div class="col-auto">
<i class="fas fa-chart-bar fa-2x text-gray-300"></i>
</div>
</div>
</div>
</div>
</div>
How could I apply what is contained in the color_border variable in that div?
Error:
<!-- Pending Requests Card Example -->
<div class="col-xl-3 col-md-6 mb-4" *ngFor="let data of miDataInterior.DatagreenhouseRecuperado; let i = index">
<div *ngFor="let color_border of color_border" class="card {{color_border}} shadow h-100 py-2">
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-warning text-uppercase mb-1">{{data.medidas[0].sensor_type[0].name_comun}}</div>
<font SIZE=3> {{data.medidas[0].marca}} </font>
<font SIZE=3>({{data.medidas[0].recvTime | date:'dd-MM-yy h:mm:ss a'}})</font>
<div class="h5 mb-0 font-weight-bold text-gray-800">{{data.medidas[0].attrValue | number:'1.0-1'}} {{data.medidas[0].sensor_type[0].medida}}</div>
</div>
<div class="col-auto">
<i class="fas fa-chart-bar fa-2x text-gray-300"></i>
</div>
</div>
</div>
</div>
</div>
Thanks for your help.
EDIT
I am testing directly on NGCLASS, the problem is that it only shows the style of the last element in the array. How can I fix this?
<div class="card shadow h-100 py-2" [ngClass]="['border-left-primary', 'border-left-info', 'border-left-warning']">
Alternate border
[ngClass]="color_border[i%3]"
A random you need make a function (you can not use Math inside the .html)
[ngClass]="getRandomColor()"
getRandomColor()
{
return this.color_border[Math.floor(Math.random()*this.color_border.length]
}
If you miDataInterior.DatagreenhouseRecuperado has a property "color" from 0 to 2 you can use
[ngClass]="color_border[data.color]"
NOTE there're severals ways to use [ngClass], see the docs
Try this..
<div *ngFor="let color_border of color_border" class="card shadow h-100 py-2 " [ngClass]="{{color_border}}">

Neet help in creating the parent/child structure in Jquery

I have the following HTML :
I'm trying to send the <p>{{ $comment->comment }}</p> to a Jquery function, upon clicking on the Edit button. I need help in completing the below structure :
Comment = event.target.parentNode.childNodes[1];
<div class=" p-3 border-top border-bottom bg-light">
<div class="d-flex align-items-center osahan-post-header">
<div class="dropdown-list-image mr-3 mb-auto"><img class="rounded-circle" src="img/p8.png" alt=""></div>
<div class="mr-1">
<div class="text-truncate h6 mb-3">{{ $comment->user->first_name }} {{ $comment->user->last_name }}</div>
<p>{{ $comment->comment }}</p>
</div>
<span class="ml-auto mb-auto">
<div class="text-right text-muted pt-1 small">{{ $comment->created_at}}</div>
</span>
</div>
<div class="post" align="right" data-postid="{{ $comment->id }}">
Edit
</div>
</div>
</div>
If you would fix your invalid HTML (as already mentioned in a comment, a <div> can't be inside a <span>), you could get the comment as follows:
document.getElementById("eid").onclick = function(e) {
let comment = e.target.closest(".p-3").getElementsByTagName("p")[0].innerHTML;
console.log(comment);
};
or, if you would use jQuery:
$("#eid").on("click", function(){
let comment = $(this).closest(".p-3").find("p").text();
console.log(comment);
});

AngularJs - On ng-click all items get affected

I'm trying to change the scope when i click on the element but when i do that all the elements get's changed
What im trying to accomplish is when i click on one of the div, i want te color of the div to change to red. this part works fine. Then i also want to the scope to change when i click on one of the divs. What is happening here is that all the scopes are changing.
<div class="col-md-3 col-sm-6 mb-3" ng-repeat="student in stuRegister.students" ng-click="stuRegister.absneceChange($index, absence)">
<div id="myDIV{{$index}}" class="card text-white bg-success o-hidden h-100" data-index="{{$index}}">
<div class="card-body">
<div class="mr-5" >
<p>{{$index + 1}}. <strong>{{student.name}}</strong></p></div>
<div class="mr-5" data-ng-model-options="stuRegister.aData.role" ><strong ng-bind="absence">Status: {{absence[0]}}</strong></div>
</div>
<a class="card-footer text-white clearfix small z-1" href="#">
<span class="float-left">Indmeld fravær</span>
<span class="float-right">
<i class="fa fa-angle-right"></i>
</span>
</a>
</div>
</div>
Js:
$scope.absence = "Tilstede";
this.absneceChange = function(index, absence){
var element = document.getElementsByClassName("card");
$scope.absence = $scope.absence === "Tilstede" ? "Fravær" : "Tilstede";
element[index].classList.toggle("bg-danger");
element[index].classList.toggle("bg-warning");
}

Categories