jquery hide method hides div but then div reappears - javascript

I have the following code where I want to hide the closest grouping div. When I click the delete button, the div disappears but then comes back (added 600 so I could see this).
I have researched and found others saying to use event.preventDefault, return false; and add href”#!’ to the <a> tag. None seem to work. I changed the .hide() to .remove() and It works, but I won't just want to hide the div and use it later in the post model binding
#model Durendal.Core.ViewModels.RoleViewModel
<div class="d-flex flex-row grouping">
<div class="flex-grow-1" style="overflow-x: auto;">
#(Html.Kendo().DropDownListFor(m => m.Id)
.DataTextField("Name")
.DataValueField("Id")
.MinLength(3)
.HtmlAttributes(new { style = "width:100%;" })
.Height(290)
.Filter(FilterType.Contains)
.AutoWidth(true)
.DataSource(source =>
{
source.Custom()
.Transport(transport => transport
.Read(read => read
.Action("GetRoles", "DataApi", new { Area = "Shared" })));
})
)
</div>
<div class="">
<a href="#!" class="btn btn-sm btn-outline-danger waves-effect remove-grouping-button">
<i class="fas fa-times"></i>
</a>
</div>
<script type="text/javascript">
(function () {
$('.remove-grouping-button').click(function (event) {
event.preventDefault();
$(this).closest('.grouping').hide(600);
return false;
});
})();
</script>
</div>
This should hide the div but it reappears

Your code works - some other code must make it re-appear.
I only post this for demonstration and will delete it when you have seen it.
Please do not vote up or accept as answer and No need to vote down either
$(function() {
$('.remove-grouping-button').click(function(event) {
event.preventDefault(); // cancel anchor click
$(this).closest('.grouping').hide(600);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class="d-flex flex-row grouping">
<div class="flex-grow-1" style="overflow-x: auto;">
Some Kendo dropdown
</div>
<div class="">
<a href="#!" class="btn btn-sm btn-outline-danger waves-effect remove-grouping-button">
<i class="fas fa-times"></i>
</a>
</div>
</div>

Related

bootstrap 5 popover with html content

I am trying to get separate the bootstrap5 popover content from the HTML attributes like you can do with other components, but I can't get it to work.
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function(popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl)
})
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<a type="button" class="btn btn-lg btn-danger" data-bs-toggle="popover">Click to toggle popover</a>
<div id="customdiv" style="display: none">
<h1> popover </h1>
</div>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.1/dist/umd/popper.min.js" integrity="sha384-SR1sx49pcuLnqZUnnPwx6FCym0wLsk5JZuNx2bPPENzswTNFaQU1RDvt3wT4gWFG" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.min.js" integrity="sha384-j0CNLUeiqtyaRmlzUHCPZ+Gy5fQu0dQ6eZ/xAww941Ai1SxSY+0EQqNXNE6DZiVc" crossorigin="anonymous"></script>
Nobody answered properly with simple JavaScript without jQuery dependency. It's important because Bootstrap 5 doesn't depend on jQuery anymore.
HTML:
<a class="btn btn-link" data-bs-toggle="popover" data-bs-placement="bottom" data-bs-content-id="popover-content" tabindex="0" role="button">
Open Popover
</a>
<div id="popover-content" class="d-none">
Popover content with <strong>HTML</strong>.
</div>
JavaScript:
const list = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
list.map((el) => {
let opts = {
animation: false,
}
if (el.hasAttribute('data-bs-content-id')) {
opts.content = document.getElementById(el.getAttribute('data-bs-content-id')).innerHTML;
opts.html = true;
}
new bootstrap.Popover(el, opts);
})
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl,{html: true})
});
None of the answers really offered me a complete solution where the popover does not appear until the data-bs-trigger event happen so this is my solution:
Element that when hovering on will have popover:
<a class="btn btn-question-tag"
data-bs-toggle="popover"
data-bs-trigger="hover focus"
data-content-id="popover-27"
href="#">
element to trigger popover
</a>
Element that its inner html will be in the popover that appears.
<div style="display: none;" id="popover-27">
<div class="popover" role="tooltip">
This is the
</div>
</div>
javascript:
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
const popoverId = popoverTriggerEl.attributes['data-content-id'];
if (popoverId) {
const contentEl=$(`#${popoverId.value}`).html();
return new bootstrap.Popover(popoverTriggerEl, {
content: contentEl,
html: true,
});
}else{//do something else cause data-content-id isn't there.
}
}
There is a simple way to put an html element in popover container
you must put the html element directly in data-bs-content tag,
and set the data-bs-html="true" to parse that content as html
and also disable the sanitize to make the content readable as html
this code works for me try it too.
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function(popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl)
})
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<a type="button" class="btn btn-lg btn-danger" data-bs-toggle="popover"
data-bs-html="true" data-bs-sanitize="false"
data-bs-content='<div class="popover fs-6" role="tooltip">
<div class="popover-body">Providing your birthday helps make sure you get the right Facebook experience for your age. If you want to change who sees this, go to the About section of your profile. For more details, please visit our Data Policy.</div></div>'>Click to toggle popover</a>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.1/dist/umd/popper.min.js" integrity="sha384-SR1sx49pcuLnqZUnnPwx6FCym0wLsk5JZuNx2bPPENzswTNFaQU1RDvt3wT4gWFG" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.min.js" integrity="sha384-j0CNLUeiqtyaRmlzUHCPZ+Gy5fQu0dQ6eZ/xAww941Ai1SxSY+0EQqNXNE6DZiVc" crossorigin="anonymous"></script>
Bootstrap v5.2.0 and laravel 8 in app.js
document.addEventListener('DOMContentLoaded', function() {
var element = document.getElementById('myPopover');
if (element) {
var popover = new bootstrap.Popover(element, {
container: 'body',
html: true,
content: function() {
return document.getElementById('popover-content').innerHTML;
},
});
}
});
Laravel blade
<a tabindex="0" type="button" data-bs-toggle="popover" data-bs-placement="bottom" aria-label="Share this article socially" id="myPopover" >
<img src="{{asset('layout/icon_return.svg')}}" alt="share icon">
</a>
<div class="pop-in" id="popover-content" style="display:none;"> <div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups">
<div class="btn-group" role="group" aria-label="First group">
<a class="btn btn-secondary" href="https://www.facebook.com/sharer.php?u={{ $item->url }}" target="_blank" rel="noopener" type="button" ><img src="{{asset('layout/facebook.svg')}}" alt="Share Page on Facebook" ></a>
<a class="btn btn-secondary" href="https://twitter.com/intent/tweet?url={{ $item->url }}%2F&text={{ $item->title }}.&hashtags=css,html" target="_blank" rel="noopener" type="button" ><img src="{{asset('layout/twitter.svg')}}" alt="Share Page on Twitter"></a>
<a class="btn btn-secondary" href="https://www.linkedin.com/shareArticle?mini=true&url={{ $item->url }}%2F&item={{ $item->title }}" target="_blank" rel="noopener" type="button" ><img src="{{asset('layout/linkedin.svg')}}" alt="Share Page on LinkedIn" ></a>
</div>
</div>
</div>
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl)
})
var popover = new bootstrap.Popover(document.querySelector('.element'), {
trigger: 'hover',
html: true,
content:function () {
return '<label>Test</label>';
},
})
Although the above answers looks fine but there is small correction here. Content option in bootstrap 5 is not working with innerHTML as it expects the type element/string/function to get the content from.
So as usual, first we will need to create div for the content with some id and then wrap it inside hidden div as this will be also shown in main flow. And then with html and content options provided by bootstrap popover, we will insert the custom popover content.
Also, instead of innerHTML, we will directly have document.getElementById('mypopover-content') as the popover content element to show as the content (and not document.getElementById('mypopover-content').innerHTML).
var popover = new bootstrap.Popover(document.querySelector('.example-popover'), {
container: 'body',
html: true,
content: document.getElementById('mypopover-content'),
})
body {
margin: 10px !important;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/js/bootstrap.bundle.min.js"></script>
<a class="btn btn-primary example-popover" role="button" tabindex="0" title="Content demonstration popover"
>Trigger popover with other html content</a>
<div hidden>
<div id="mypopover-content">
<p>This is the custom popover html content that should be inserted into my example popover</p>
<button type="button" class="btn btn-primary">and the button as well</button>
</div>
</div>
var hideDiv = document.getElementsByClassName('hide')[0].style.visibility = 'hidden'
var popoverBtn = document.getElementById('btn-action')
var popover = new bootstrap.Popover(popoverBtn, {
placement: 'bottom',
html: true,
content: function() {
return document.getElementById('id-content-div');
}
})
var showDiv = document.getElementsByClassName('hide')[0].style.visibility = 'visible'
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<a type="button" class="btn btn-lg btn-danger" id="btn-action">Click to toggle popover</a>
<div id="id-content-div" class="hide">
<h1> popover </h1>
<p>Hello popover world</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.1/dist/umd/popper.min.js" integrity="sha384-SR1sx49pcuLnqZUnnPwx6FCym0wLsk5JZuNx2bPPENzswTNFaQU1RDvt3wT4gWFG" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.min.js" integrity="sha384-j0CNLUeiqtyaRmlzUHCPZ+Gy5fQu0dQ6eZ/xAww941Ai1SxSY+0EQqNXNE6DZiVc" crossorigin="anonymous"></script>
$(function() {
var options = {
html: true,
title: "Optional: HELLO(Will overide the default-the inline title)",
//html element
content: $("#popover-content")
//Doing below won't work. Shows title only
//content: $("#popover-content").html()
}
var exampleEl = document.getElementById('example')
var popover = new bootstrap.Popover(exampleEl, options)
})
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.5.0/font/bootstrap-icons.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="popover-content">
<div class="input-group">
<input type="text" class="form-control form-control-sm" placeholder="Search" name="search">
<div class="input-group-btn">
<button class="btn btn-danger" type="submit">
<i class="bi bi-search"></i>
</button>
</div>
</div>
<div class="col-sm-8"></div>
<button class="btn btn-success m-3">Button</button>
<input type="submit" class="btn btn-danger" placeholder="Button red">
</div>
<a id="example" tabindex="0" class="btn btn-lg btn-danger" role="button" data-bs-toggle="popover" title="Default: Html inside popover" data-bs-content="And here's some amazing content. It's very engaging. Right? This is default, but Can be empty">Html inside popover</a>
You can't have a zero length title and content. From the Bootstrap docs...
"Zero-length title and content values will never show a popover."
<a type="button" class="btn btn-lg btn-danger"
data-bs-toggle="popover"
data-bs-title="Hello">Click to toggle popover</a>
Demo

Dynamically determine which button of a particular class has been clicked with jquery

A demo of my dilemma here
Let's say I have the following html:
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<body>
<div class="main" id="thingSection">
<h1>
Test Header
</h1>
<button class="btn-icon"><i class="fa fa-fw fa-lg fa-windows"></i> <i class="fa fa-fw fa-lg fa-toggle-off"></i> <i class="fa fa-fw fa-lg fa-apple"></i></button>
<div class="content" id="content1">
Some content
</div>
</div>
<hr />
<div class="main" id="thingSection1">
<h1>
Another Test
</h1>
<button class="btn-icon"><i class="fa fa-fw fa-lg fa-windows"></i> <i class="fa fa-fw fa-lg fa-toggle-off"></i> <i class="fa fa-fw fa-lg fa-apple"></i></button>
<div class="content" id="content2">
Some content
</div>
</div>
<hr>
<div class="main" id="thingSection2">
<h1>
Another test, you say?
</h1>
<button class="btn-icon"><i class="fa fa-fw fa-lg fa-windows"></i> <i class="fa fa-fw fa-lg fa-toggle-off"></i> <i class="fa fa-fw fa-lg fa-apple"></i></button>
<div class="content" id="content3">
Some content
</div>
</div>
</body>
</html>
I am using the following jquery to change the toggle icon from FontAwesome from off to on:
$(function() {
$('.btn-icon').click(function() {
if ($(this).find($(".fa")).hasClass('fa-toggle-off')) {
$("i.fa-toggle-off").toggleClass('fa-toggle-on');
} else {
$("i.fa-toggle-on").toggleClass('fa-toggle-off');
}
});
});
When I click the button to toggle the icon, it works as expected, i.e. it changes all of the buttons on the page. However, I would like to dynamically determine which button has been pressed, and then change the content of a child div based on the position of the switch.
I want to avoid hardcoding id's for each button to avoid a ton of if/else statements in the script that must be updated each time I, say, add a new button or a new section. That is to say, I want to dynamically detect which button has been pressed, and affect only that button and its children.
I've noticed that console.log(this) yields only the HTML for the particular button that has been pressed, not all of the buttons.
I'm a novice with jquery. I haven't been able to find a solution to this problem yet, and I feel like there has to be a way to do this dynamically without hardcoding IDs.
EDIT: I've accomplished (partially) what I want to do with the following code:
$(function() {
$('.btn-icon').click(function() {
var t = $(this).find('.is-toggle');
if (t.hasClass('fa-toggle-off')) {
t.addClass('fa-toggle-on');
t.removeClass('fa-toggle-off');
}
else {
t.addClass('fa-toggle-off');
t.removeClass('fa-toggle-on');
}
});
});
Looks like I just didn't understand what exactly $(this) was (:
All you need is $(this) that selects the element that triggered the event. From there you can select down to the div you want.
EDIT: Here is how that might look in code, I pulled this from your fiddle and edited it
$(function() {
$('.btn-icon').click(function() {
$(this).children('.fa-toggle-off, .fa-toggle-on').toggleClass('fa-toggle-on fa-toggle-off');
});
});

Javascript not triggering on modal open with Twig Template

Note: I've tried the various solutions found online for my issue, but none of them have worked.
I am trying to pass content from a table where each row has its own button to edit the content in that row. The button opens a Twitter Bootstrap dropdown, which has two buttons, one being the "Edit" button. The edit button opens a modal which has a text-area input. I want the text-area to have the current text present in the table for editing. I am using PHP with Symfony for the forms and Twig for the page rendering.
the button that triggers the modal
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<button class="btn btn-sm dropdown-item edit-button" data-toggle="modal" data-target="#announcementEditModal" data-id="{{ announcement.id }}" data-content="{{ announcement.content }}" type="button">
<div class="announcement-actions">
<span class="fas fa-pencil-alt"></span> Edit announcement
</div>
</button>
The modal
<div class="modal fade" id="announcementEditModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header announcement-header">
<h5 class="modal-title" id="exampleModalLabel"><span class="fas fa-edit"></span> Edit new announcement</h5>
</div>
<div class="announcement-card-header card m-3 border-0">
<div class="announcement-card-header card-body border-0 p-1">
<span class="fa fa-info-circle fa-lg header-icon"></span>
<h5 class="align-header">ANNOUNCEMENT TEXT</h5>
</div>
<div class="announcement-card-body modal-body card border-0">
{{ form_start(editForm) }}
<div class="announcement-card-body">
<label for="exampleInputEmail1">ANNOUNCEMENT (SUPPORTS MARKDOWN)</label>
<textarea class="form-control" id="announcementText" rows="5" name="content"></textarea>
</div>
</div>
</div>
<div class="card-footer border-0 bg-white pt-0">
<div>
{{ form_widget(editForm.edit, {'left_icon': 'fas fa-check'}) }}
<button type="button" class="btn btn-light" data-dismiss="modal" aria-label="Close">
Cancel
</button>
</div>
</div>
{{ form_end(editForm) }}
</div>
</div>
</div>
The JavaScript
<script type="text/javascript">
$(".edit-button").click(function(){
var content = $(this).data("content");
alert(content);
});
$('#announcementEditModal').on('shown.bs.modal', function () {
alert("modal open");
document.getElementById("#announcementText").val(content);
})
</script>
The alert("modal open") does not fire.I have tried'shown.bs.modal'and'show.bs.modal'`. I'm using Bootstrap 4.12
EDIT: Solution: Once I moved the JS to an announcements.js file where I was doing some stuff with my forms the trigger works.
It appears you either have an incomplete html code or have not shared it all with us.
dropdown-menu does not have a closing div.
wrap dropdown-menu inside dropdown or btn-group.
var content will not be available inside your shown.bs.modal function, so declare it globally, not a very good advice but for simplicity sake.
Fix Javascript error, since you are using jQuery, use it.
document.getElementById("#announcementText").val(content); // val is not function
Replace with
document.getElementById("#announcementText").value = content;
$("#announcementText").val(content); // or jQuery way
And here is the fiddle: https://jsfiddle.net/7onyuw9f/1/
Attempt 2
Below is an example of revealing module pattern to show how you can avoid global variables and also a lot cleaner. You can read more about this pattern here
// Revealing Module Pattern
var MyProject = MyProject || {}; // Your global object
MyProject.Modal = function() { // Namespacing to Modal
var content = ""; // now content is local to this function;
var onEditClick = function() {
$(".edit-button").click(function() {
content = $(this).data("content");
alert(content);
});
};
var onModalShow = function() {
$('#announcementEditModal').on('shown.bs.modal', function() {
alert("modal open");
// $("#announcementText").val(content); <-- jQuery way
document.getElementById("announcementText").value = content;
});
};
var init = function() {
onEditClick();
onModalShow();
};
return {
init: init // expose this for other functions to call
}
}();
$(document).ready(function() {
MyProject.Modal.init();
});
And the fiddle https://jsfiddle.net/x28s3uc9/1/

Magnific Pop up wont close when you press Cancel on the Modal

I am using Magnific Pop up on a project, currently I have it on a ASP MVC project as a Modal:
Modal
div id="js_DeleteNewSongsPopup" class="theme-primary ajax-form popup-basic admin-form mfp-with-anim modalPopup">
<div class="panel">
<div class="panel-heading">
<span class="panel-title">
<i class="fa fa-ban "></i>Reject Selected Song
</span>
</div>
#* Information Body *#
<div class="panel-body p25">
<div class="section row">
<div class="col-md-12 text-center">
<h3>
Are you sure you want to <b class="text-danger">reject</b> the selected Songs?
</h3>
<p>
Please note, these will be <b class="text-danger">deleted</b> and no longer accessable
</p>
</div>
</div>
</div>
#* Form Body *#
<div class="panel-footer">
<div class="text-center">
<fieldset>
<input type="button" class="btn btn-primary js_CancelForm" value="Cancel" data-bind="click: function(){ $.magnificPopup.close(); }">
<input type="button" class="btn btn-danger js_DeleteNewSongsButton" value="Delete" data-bind="click: $root.submitDeleteNewSongs">
</fieldset>
</div>
</div>
</div>
<button title="Close (Esc)" type="button" class="mfp-close">×</button>
JavaScript
/* Delete New Songs Popup*/
$(document).on("click",
".js_DeleteNewSongs",
function (e) {
e.preventDefault();
var popup = $("#js_DeleteNewSongsPopup");
$.magnificPopup.open({
removalDelay: 500, //delay removal by X to allow out-animation,
items: {
src: $(popup)
},
callbacks: {
beforeOpen: function (e) {
this.st.mainClass = 'mfp-slideUp';
},
close: function () {
}
},
midClick: true
// allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source.
});
return false;
});
Any ideas as there is no console errors being reported. I am also unsure why it is working on another page, when the mark-up is identical
Try:
$('body').removeClass('panel-body p25');
Or
$('body').removeClass('theme-primary ajax-form popup-basic admin-form mfp-with-anim modalPopup');
Basically you need to remove the "modal" class.
Ended up using:
$('.js_CancelForm').on("click", function () {
$.magnificPopup.close();
});
Now the Popup closes as expected.

Javascript toggle hide and show buttons in a loop Laravel 5

I am writing a Laravel 5 project with a comment section code below
#foreach($Comment as $Comment)
<div id="comment-{!! $Comment->comments_id !!}" class="comment-wrapper">
<div class="btn btn-lg btn-info btn-xs" class="show">Show</div>
<div class="btn btn-lg btn-success btn-xs" class="hide">Hide</div>
<div class="btn btn-lg btn-warning btn-xs" class="toggle">Toggle</div>
<div class="watch" class="jumbotron alert-info">
<ul class="list-group">
<li class="list-group-item list-group-item-success">{!! $Comment->author !!}</li>
<li class="list-group-item"> {!! $Comment->text !!}</li>
</ul>
#if ($Comment->author == Auth::user()->name)
<p>Delete</p>
#endif
<h6><small>CREATED ON: {!! $Comment->created_at !!}</small></h6>
</div>
</div>
#endforeach
and I have a javascript file which looks like this
$(document).ready(function () {
$('.show').click(function () {
$(this).closest('.comment-parent').find('.watch').show('slow');
});
$('.hide').click(function () {
$(this).closest('.comment-parent').find('.watch').hide('slow');
});
$('.toggle').click(function () {
$(this).closest('.comment-parent').find('.watch').toggle('slow');
});
});
The trouble is the toggle/hide javascript function only works on one set of buttons and hides all of the comments. I want to have the set of buttons that work for each comment individually. I've tried to increment the watch class and buttons div id by adding 1 and incrementing it for each comment but can't get it to work. Any help would be appreciated thanks.
You may try something like this:
$('#show').click(function () {
$(this).next('.watch').show('slow');
});
Try same approach for other methods, so only the next first div with class of watch will be acted and also, you could have wrapped each set in a single parent container using a unique id attribute in addition to a class, for better grouping. For example:
#foreach($Comment as $Comment)
<div id="comment-{{$comment->id}}" class="comment-wrapper">
<div class="btn btn-lg btn-info btn-xs show">Show</div>
<!-- More... -->
<div class="watch" class="jumbotron alert-info">
<!-- More... -->
</div>
</div>
#endforeach
This way, you could have done the jQuery slecting more specifically, for example:
$('#show').click(function () {
$(this).closest('.comment-parent').find('.watch').show('slow');
});
Update (Thanks to haakym for pointing me that): Also, an id must be unique so instead of using id='show' use it as a class and then use:
$('.show').click(function () {
$(this).closest('.comment-parent').find('.watch').show('slow');
});

Categories

Resources