Binding an event to content loaded using jQuery Load - javascript

I'm creating a prototype application. I wanted to template my header and footer over html files. I'm loading these in using jQuery load.
In my index file I have this in the first part of my body:
<!--COMMON HEADER ------------- -->
<header id="common-include-header" class="blade child ns">
</header>
I'm including via a document called includes.js which is listed before header.js in my head/script tags. Here is the includes.js like so:
$(document).ready(function () {
$("#common-include-header").load("includes/header.html");
$("#common-include-footer").load("includes/footer.html");
});
Here is my header.html:
<div class="blade-content flexr xc sb">
<img src="img/logo100.svg"></img>
<div class="child g">
<form class="search-form flexr jc">
<input class="location" value="Auckland" />
<input class="context" placeholder="Find something" />
<button class="child ns"><i class="fa fa-search"></i></button>
</form>
</div>
<button class="search-toggle"><i class="fa fa-search"></i></button>
<div class="child ns">
<button class="sign-in-button pill outline pink">Sign in</button>
<button class="user-signed-in flexr xc hide">
<p>test#gmail.com</p>
<img src="img/av.png"></img>
<i class="fa fa-chevron-down"></i>
</button>
</div>
<nav class="signed-in-nav flexc">
<button type="button" class="dropdown-menu child ns">Favourites</button>
<button type="button" class="dropdown-menu child ns">Reviews</button>
<button type="button" class="dropdown-menu child ns">Businesses</button>
<button type="button" class="dropdown-menu sign-out child ns">Sign out</button>
</nav>
</div>
And my header.js
$(document).ready(function () {
//hide/show mobile search
$(".search-toggle").on("click", function () {
if ($(".toggle-search").hasClass('open')) {
$(".toggle-search").removeClass("open");
} else {
$(".toggle-search").addClass("open");
};
});
//hide/show sign in
$(".sign-in-button").on("click", function () {
$(".sign-in-button").addClass("hide");
$(".user-signed-in").removeClass("hide");
});
//hide/show user menu
$(".user-signed-in").on("click", function () {
if ($(".signed-in-nav").hasClass("open")) {
$(".signed-in-nav").removeClass("open");
$(".user-signed-in").removeClass("open");
} else {
$(".signed-in-nav").addClass("open");
$(".user-signed-in").addClass("open");
};
});
//sign out
$("button.sign-out").on("click", function () {
$(".signed-in-nav").removeClass("open");
$(".user-signed-in").removeClass("open");
$(".user-signed-in").addClass("hide");
$(".sign-in-button").removeClass("hide");
});
});
My problem is that the event handlers aren't binding to .sign-in-button. I would have thought since I used jQuery .on this would work. I can't figure it out. Where am I going wrong?

jQuery's load has a callback function...
Try this:
$("#common-include-header").load("includes/header.html", function(){
// bind to header code here
});
$("#common-include-footer").load("includes/footer.html", function(){
// bind to any footer code here
});
You can also use .toggleClass() instead of having separate lines to add or remove class names.
//hide/show mobile search
$(".search-toggle").on("click", function () {
var isOpen = $(".toggle-search").hasClass('open');
$(".toggle-search").toggleClass("open", !isOpen);
});
//hide/show sign in
$(".sign-in-button").on("click", function () {
$(".sign-in-button").addClass("hide");
$(".user-signed-in").removeClass("hide");
});
//hide/show user menu
$(".user-signed-in").on("click", function () {
var isOpen = $(".signed-in-nav").hasClass("open");
$(".signed-in-nav").toggleClass("open", !isOpen);
$(".user-signed-in").toggleClass("open", !isOpen);
});
//sign out
$("button.sign-out").on("click", function () {
$(".signed-in-nav, .user-signed-in").removeClass("open");
$(".user-signed-in").addClass("hide");
$(".sign-in-button").removeClass("hide");
});

As you are loading your html on DOM ready, all your javascript files are already loaded and your header.html is being loaded after that. So your header.js can not locate the element using $(".search-toggle").on("click", function () { . Here you have to use $(document).on("click",".search-toggle", function () {

Related

Click Button is not working on a div in asp.net partial page

I am using JQUERY 3.4.1 in .NET MVC project. When I took partial page then on click is not working. Here I have put my tried code's. when I am using $(document).on('click') then it is creating another issue that it is opening tab data also. So I avoid it.
$(document).on('click', '.dummy_current_card_header_dropDownBtn', function () {
$(this).next('.dummy_current_card_header_dropDownBtn_item').toggle();
});
// project_lesting_current_card_header_dropDownBtn
$('.dummy_current_card_header_dropDownBtn').on('click', function () {
$(this).next('.dummy_current_card_header_dropDownBtn_item').toggle();
});
$('.dummy_current_card_header_dropDownBtn').click(function () {
$(this).next('.dummy_current_card_header_dropDownBtn_item').toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="current_card_header_btn">
<span class="current_card_header_dropDownBtn dummy_current_card_header_dropDownBtn" type="button" role="button"><img src="~/images/project/icon/action_icon.png" style="width: 14px;"></span>
<div class="current_card_header_dropDownBtn_item dummy_current_card_header_dropDownBtn_item">
<ul>
<li>Review</li>
<li>Duplicate</li>
<li>Archive</li>
<li>Delete</li>
</ul>
</div>
</div>
It is solved. I used onclick in HTML.
here is the code.
function CurrentTabDropDown(status) {
$(status).next('.dummy_current_card_header_dropDownBtn_item').toggle();
}

TypeError: menu is not a function

I have this error that I can't find why it is not being called properly menu is a function yet it says it is not. error (TypeError: menu is not a function) I tried to move it before the HTML that calls it but that did not work.
<script>
var dropdown = document.querySelector("nav .dropdown");
var menu = document.querySelector("nav div .menu");
function menu()
{
if(dropdown.style.display === "none")
{
dropdown.style.display = "grid";
}
else
{
dropdown.style.display = "none";
}
} </script>
<input class="button" type="button" onclick="location.href='Controller/logout.php';" value="logout" /> <nav>
<div class="content">
<div class="links">
Home
Portfolio
Reviews
</div>
<i class="material-icons menu" onclick="menu()">menu</i>
</div>
<div class="dropdown">
Home
Portfolio
Reviews
</div> </nav>
That probably returns an error, since the naming issues.
Menu is not a function because you first initialize it with var and then redefine it with function.
Try renaming either of variables (or even remove the first one, since it's never used)
it's not working because you declare "menu" as html class and JS function.
just rename your function at both place.
<i class="material-icons menu" onclick="menu()">menu</i>
to
<i class="material-icons menu" onclick="menuFunc()">menu</i>
also
function menu()
to
function menuFunc()

Second execution follows href

With a list of products, and once a 'remove from wishlist' button is clicked, it then removes that product from said product list, along with an AJAX request to the back-end for it to be removed via SQL.
The first click works, the jQuery executes and the product is then removed. The second click on the same type of button for any product, then loads the href instead of executing the jQuery, it's meant to execute the jQuery.
I've tried calling it as a static function from the anchor onclick="return removeFromWishlist();"
Have also tried executing the jQuery on the anchor link click via the jQuery event instead of the button tag itself.
jQuery('.button-wishlist').on('click', function (index) {
event.preventDefault();
// Calls the AJAX to remove it from the back-end via SQL etc
// The response is JSON within the following call
removeProductAjax(this);
console.log('removing product from the wishlist');
// Get the cell position of the product to remove from the wishlist
var position = jQuery(this).parent().parent().parent().data('cell');
var html = [];
var cells = 0;
jQuery('.wishlist_container .col-md-4').each (function () {
//
if (jQuery(this).data('cell') == position) {
cells++;
}
else if (jQuery(this).data('cell') !== undefined) {
html.push(jQuery(this).html());
cells++;
}
});
var upto = 0;
jQuery('.product-row').each (function () {
var self = this;
// Repopulate all the product lists excluding the one removed
jQuery(self).children().each (function () {
jQuery(this).html(html[upto]);
upto++;
});
});
// Then clear everything from upto and onwards!
console.log('cells: ' + cells);
console.log('upto: ' + upto);
// let's change from array to 'standard' counting
upto--;
// Remove the last element!
jQuery('.product-row').find('[data-cell=' + upto + ']').remove();
// Check for any empty rows
jQuery('.product-row').each (function () {
if (jQuery(this).children().length == 0) {
jQuery(this).remove();
}
});
});
The HTML is basically:
<div class="row product-row">
<div class="row product-row"><div class="col-md-4" data-cell="0">
<h1>product 1</h1>
<a href="./page.php?page=cart&unwish=660986" data-index="660986" class="wishlist-button" onclick="return removeProductFromWishlist(this);">
<button name="wishlist" class="btn button-wishlist" data-type="remove">Remove from Wishlist</button>
</a>
</div>
<div class="col-md-4" data-cell="1">
<h1>product 2</h1>
<a href="./page.php?page=cart&unwish=661086" data-index="661086" class="wishlist-button" onclick="return removeProductFromWishlist(this);">
<button name="wishlist" class="btn button-wishlist" data-type="remove">Remove from Wishlist</button>
</a>
</div>
<div class="col-md-4" data-cell="2">
<h1>product 3</h1>
<a href="./page.php?page=cart&unwish=661067" data-index="661067" class="wishlist-button" onclick="return removeProductFromWishlist(this);">
<button name="wishlist" class="btn button-wishlist" data-type="remove">Remove from Wishlist</button>
</a>
</div>
</div>
I'm expecting it to execute the jQuery each time the "remove from wishlist" button is clicked, no matter what product, no matter what order. So, you can unwish many products, one after the other using AJAX / jQuery.
Follow all my comments under your Question...
And I think this is all the code you need.
PHP (I used i.e: ../removeProduct.php?id=) should respond with some JSON like:
// PHP does here some DB deletions or fails.
// Send back to AJAX the deleted item ID (or null)
// and some (error?) message
echo json_encode(['id' => $id, 'message' => $message]);
exit;
// No more PHP here. We exit.
// jQuery will collect that JSON response as `res`
jQuery(function($) {
function removeProductAjax(id) {
$.get("../removeProduct.php?id=" + id, 'json').always(function(res) {
if (res.statusText === 'error') { // General error (path invalid or something...)
return alert(`Error: Cannot remove product ID: ${id}`); // and exit function
}
if (!res.id) { // Something happened
return alert(res.message); // Alert PHP's error message and exit function.
}
// All OK. Remove item from products
$(".product-row").find(`[data-id="${res.id}"]`).remove();
});
}
$('.product-row').on('click', '.product-remove', function(ev) {
ev.preventDefault();
removeProductAjax($(this).data('id'));
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<div class="row product-row">
<div class="col-md-4" data-id="660986">
<h3>product 1</h3>
<button type="button" class="btn product-remove" data-id="660986">Remove from Wishlist</button>
</div>
<div class="col-md-4" data-id="661086">
<h3>product 2</h3>
<button type="button" class="btn product-remove" data-id="661086">Remove from Wishlist</button>
</div>
<div class="col-md-4" data-id="661067">
<h3>product 3</h3>
<button type="button" class="btn product-remove" data-id="661067">Remove from Wishlist</button>
</div>
</div>
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

Using jQuery to display each content of a button when clicked on

Am working on practice work to improve myself
I created a sidebar using jquery. Inside my sidebars I have 3 buttons.
Am trying to do something like when I click on the first button I want it to show me the contents inside the first button clicked
<div>
<li Id = ‘list-1’ class = ‘btn btn-outline-success’> </li>
<li Id = ‘list-2’ class = ‘btn btn-outline-success’> </li>
<li Id = ‘list-3’ class = ‘btn btn-outline-success’> </li>
</div>
I want each button to display its contents
Simple version (seeing as your code doesn't offer much direction)
<div>
<button id= "list-1" class="click-button btn btn-outline-success" value="Bicycle 1">Button</button>
<button id="list-2" class="click-button btn btn-outline-success" value="Bicycle 2">Button</button>
<button id="list-3" class="click-button btn btn-outline-success" value="Bicycle 3">Button</button>
</div>
<script>
$(document).ready(function () {
$('body').on('click', '.click-button', function () {
alert(this.value)
})
})
</script>

#Html.Action causes javascript to load multiple times

I inherited an application and trying to figure out way scripts on the tabs are loading more than once.
It is an basic bootstrap tab feature that loads partial views.
<ul class="nav nav-tabs" id="myTab">
<li class="active"><a data-target="#home" data-toggle="tab">Home</a></li>
<li><a data-target="#reputation" data-toggle="tab">Reputation</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="home">
#Html.Action("SocialConfig", "Admin", new {area = "Admin", accountID = ViewBag.AccountID})
</div>
<div class="tab-pane" id="reputation">
#Html.Action("ReputationConfig", "Admin", new { area = "Admin", accountID = ViewBag.AccountID })
</div>
</div>
There is an JavaScript file included on each partial view. Each script will get loaded as many times there are #Html.Action
So for instance I have 2 #Html.Action so the script on the SocialConfig view will load twice and the script on the ReputationConfig will also load twice.
How can i stop this silly behavior.
If you are using jQuery to add some event handlers then check if the selectors are filtering elements of both partials views. If so you should change your selector in way that it is contextualized to your partial view.
Ex:
Partial view 1
<div>
<button class="button" type="button">Click me</button>
</div>
<script>
$(".button").click(function () { alert("click on button") });
</script>
Partial view 2
<div>
<a class="button">Click me</a>
</div>
<script>
$(".button").click(function () { alert("click on link") });
</script>
A example of contextualized events:
Partial view 1
<div id="my-partial-view-1-container">
<button class="button" type="button">Click me</button>
</div>
<script>
$("#my-partial-view-1-container").find(".button").click(function () { alert("click on button") });
</script>
Partial view 2
<div id="my-partial-view-2-container">
<a class="button">Click me</a>
</div>
<script>
$("#my-partial-view-2-container").find(".button").click(function () { alert("click on link") });
</script>
When working with partialview try to avoid loading script, add it instead in the main view. Why not just add it in the current view?

Categories

Resources