How to ignore javascript until button is click, then run - javascript

I have been adding ticket sales to our home page but it has dramatically slowed down the site. We have about 1250 shows for this season and even though adding this to the home page sales has gone up but people are complaining about the speed.
Currently I'm using the javascript:showhide to hold the ticket purchase information in a hidden div that shows when you click buy tickets.
I would like to have it NOT run anything in the hidden div unless the buy tickets button is click. Then it would pull the ticketing information and populate the div.
We will have about 300 of the ticketing scripts on the page at one time like Show1-Oct, Show2-Oct, Show3-Oct, Show1-Nov, Show2-Nov, Show3-Nov and so on.
Any ideas or help is greatly appreciated.
<div class='topShow bg-Show-Main'>
<a href='Show1.php'><img alt='Show1' title='Show1' src='images/show/Show1.jpg'>
<p class='title'>Show1</p>
<p>Opens October 30th</p>
</a>
<div class='btnContainer2'>
<a class='btn1' style="text-align: left; width:49%; display: inline-block;" href='Show1.php'>More info</a>
<a class='btn2 red' style="text-align: right; width:50%; display: inline-block;" href="javascript:showhide('Show1-Oct')">Buy Tickets</a>
</div>
<div id="Show1-Oct" style="display:none;">
<script type="text/javascript" src="http://website.com/booking/index.php?controller=FrontEnd&action=ActionLoad&theme=10&view=list&icons=T&cid=15&locale=1"></script>
</div>
<div class='clear'></div>
</div>
<div class='topShow bg-Show-Main'>
<a href='Show2.php'><img alt='Show2' title='Show2' src='images/show/Show2.jpg'>
<p class='title'>Show2</p>
<p>Opens October 31st</p>
</a>
<div class='btnContainer2'>
<a class='btn1' style="text-align: left; width:49%; display: inline-block;" href='Show2.php'>More info</a>
<a class='btn2 red' style="text-align: right; width:50%; display: inline-block;" href="javascript:showhide('Show2-Oct')">Buy Tickets</a>
</div>
<div id="Show2-Oct" style="display:none;">
<script type="text/javascript" src="http://website.com/booking/index.php?controller=FrontEnd&action=ActionLoad&theme=10&view=list&icons=T&cid=16&locale=1"></script>
</div>
<div class='clear'></div>
</div>

Loading up a separate javascript file for each element on the page is a really bad idea.
A more sane design would be to have a single script that makes an ajax call for the necessary data for each listing when needed (when the user clicks that 'buy tickets' button) and injects it into the page. Something along these lines: (some extraneous HTML removed from your sample code, but you'll get the idea)
$('.btn2').on("click", function() {
var myId = $(this).parent().next().attr("id"); // or store this as a data attribute on the button or somewhere else conveniently accessible
console.log("Get data for ", myId);
$.get("/whatever?id=" + myId, function(response) {
// assuming that ajax call returns html, just inject it into the div:
$('#" + myId').html(response);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='topShow bg-Show-Main'>
<div class='btnContainer2'>
<a href="#" class='btn2 red'>Buy Tickets</a>
</div>
<div id="Show1-Oct">
</div>
<div class='clear'></div>
<div class='btnContainer2'>
<a href="#" class='btn2 red'>Buy Tickets</a>
</div>
<div id="Show2-Oct">
</div>
<div class='clear'></div>
</div>

Related

Avoid JavaScript Replication in partial views

This code is used to remove a cart-item from a partial view.
$(document).on('click', '.RemoveLink', (function (e) {
e.preventDefault();
var recordToDelete = $(this).attr("data-id");
var itemID = $(this).attr("data-itemid");
if (recordToDelete != '') {
$.post("/ShoppingCart/RemoveFromCart", { "id": recordToDelete, "itemID": itemID },
function () {
$('.container-cart').load('#Url.Action("cartDropDown","ShoppingCart")', function () {
$('.cart-dropdown').css('display', 'inline-block');
}
);
});
}
}));
This works well for the first iteration but from the second iteration on-wards, every click of a remove of an item is resulting in deletion of 2 items of a kind. Suppose we had 4 items of pencils and 8 items of pens. Clicking delete pencil button once will result in deletion of 2 pencils and vice versa.
This is probably because of the logic used. Following is the html that is rendered when $('.container-cart').load('#Url.Action("cartDropDown","ShoppingCart")' executes:
#model OnlineStore.ViewModels.ShoppingCartViewModel
<div class="container-cart">
#if (Model.ItemCount == 0)
{
<div>
<span>
There are no items in your cart. Continue shopping.
</span>
</div>
}
else
{
<ul class="cart-dropdown">
<li>
<div class="cart-items cart-caption">
<ul>
#foreach (var i in Model.CartItems)
{
<li id="list-item-#i.item.ItemID">
<div class="container-fluid item-wrap" style="position: relative">
<div class="item-remove">
<a href="#" class="RemoveLink"
data-id="#i.RecordID" data-itemid="#i.item.ItemID">
x
</a>
</div>
<div class="col-md-2 item-img">
<div class="row-cart">
<img alt="" id="cartImg" height="71" width="75" src="#i.item.ImageUrl">
</div>
</div>
<div class="col-md-5 item-info">
<div class="row-cart">
<div class="brand-name">
<a href="#" class="brandName">
#i.item.BrandName
</a>
</div>
<div class="product-name">
<a href="#" class="productName">
#i.item.ItemName
</a>
</div>
<div class="product-qty">
<p class="productQTY" id="item-count-#i.item.ItemID">
#i.Count x #i.item.ItemPrice
</p>
</div>
</div>
</div>
<div class="col-md-5 price-info">
<div class="row-cart" style="margin-top: 10px">
<div class="col-md-6">
<div class="row-mrp">
<span class="cartItemPrice" id="item-total-#i.item.ItemID">
Rs #(#i.Count * #i.item.ItemPrice)
</span>
</div>
</div>
</div>
</div>
</div>
</li>
}
</ul>
</div>
</li>
<li class="clearfix">
<div class="col-md-6">
<div class="row-cart sub-cost" style="background: #fff; margin-left: -10px; margin-right: 0">
<p>
Sub Total :
<span style="float: right">
Rs
<span class="ng-binding"></span>
</span>
</p>
<p>
Delivery Charge :
<span qa="delChargeMB" style="float: right">Free</span>
</p>
</div>
<div class="row-cart cart-chkout-btn">
<button type="button">View Basket & Checkout</button>
</div>
</div>
</li>
</ul>
}
</div>
This html is the partial view that is initially rendered when user clicks a button to view the cart-items. So when user clicks on 'remove an item' button on this partial view, an ajax call is sent to server to remove an item from the cart-items and on success, load the UI again by rendering this partial view once again with new values from the database.
All this is working fine for the first iteration of the deletion of an item from the cart-item list. But when I'm deleting an item again as a second deletion, code is running twice. I'm guessing this is because <div class="container-cart"> is rendered twice on the page as after the first deletion, I can see it on the live DOM inside the browser that <div class="container-cart"> is encolsed inside another <div class="container-cart"> and then the normal elements are rendered in sequence. I'm guessing maybe that's why javaScript is rendered twice or running twice.
Please suggest what you think about it and help me resolve it.
Thanks in advance
After deletion of an item try to use location.reload(); instead of hitting the MVC action method again!

Selecting the first instance of a html class with jQuery

I'm having some trouble with jQuery overwriting the elements of a particular parent class. For instance, I have two classes that have the same name but I am looking only to use the first instance for a particular purpose and then the others for something else, but the data inside keeps being overwritten by the next function I am using. I think I know why it is doing it, I'm just unsure of how to fix it so it doesn't.
Here is my jQuery code:
function buildFriendStatus() {
$.getJSON('/members/feed/get-friend-status', function(data) {
var notFirstElement = $('.w3-container.w3-card-2.w3-white.w3-round.w3-margin:not(first)')
$.each(data, function(i, item) {
var element = notFirstElement.eq(i);
element.find('h4').html(data[i].username);
element.find('p').html(data[i].status);
element.find('img').attr('src', data[i].images);
});
}).fail(function(response) {
console.log(response.fail);
});
}
function buildSelfStatus() {
$.getJSON('/members/feed/list-own-status', function(data) {
$.each(data, function(i, item) {
$('.w3-container.w3-card-2.w3-white.w3-round.w3-margin:first').find('h4').html(data[i].username);
$('.w3-container.w3-card-2.w3-white.w3-round.w3-margin:first').find('p').html(data[i].status);
$('.w3-container.w3-card-2.w3-white.w3-round.w3-margin:first').find('img').attr('src', data[i].images);
});
}).fail(function(response) {
console.log(response.fail);
});
}
setInterval(function() {
buildFriendStatus();
}, 1000);
and then the html/calling of the functions
<script type="text/javascript">
buildSelfStatus();
buildFriendStatus();
</script>
<!-- always have this first (sticky) for the user status -->
<div class="w3-container w3-card-2 w3-white w3-round w3-margin">
<h4></h4>
<p></p>
<div class="w3-row-padding" style="margin: 0 -16px;">
<div class="w3-half">
<img src="" style="width: 100%; height: 200px;" alt="<?php echo $this->identity() . "'s image"; ?>" class="w3-margin-bottom w3-round w3-border">
</div>
</div>
</div>
<div class="w3-container w3-card-2 w3-white w3-round w3-margin">
<h4></h4>
<p></p>
<div class="w3-row-padding" style="margin: 0 -16px">
<div class="w3-half">
<img src="" style="width: 100%; height: 200px;" alt="<?php echo "Image"; ?>" class="w3-margin-bottom w3-round w3-border">
</div>
</div>
<button type="button" class="w3-btn w3-theme-d1 w3-margin-bottom">
<i class="fa fa-thumbs-up"></i> Like
</button>
<button type="button" class="w3-btn w3-theme-d2 w3-margin-bottom">
<i class="fa fa-comment"></i> Comment
</button>
</div>
Here is a screenshot of the issue.
Updated screenshot (shows the first image but not the other result(s) now)
Any help would be appreciated
Thanks!
Oh, on another note, is there a way to use jQuery to put data inside the class but have the class be shown more than once without overwriting the data previously added but only have one <div> element with the class name? Sort of like the screenshot attached but just not overwriting each class the same time. Just curious as I couldn't find anything regarding this. I guess I mean build the div element and it's child elements dynamically based on the results retrieved via $.getJSON.
$(".getfirst").click(function(){
alert($(".testdiv").first().text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="testdiv">
33
</div>
<div class="testdiv">
44
</div>
<div class="testdiv">
55
</div>
<div class="testdiv">
66
</div>
<div class="getfirst" style="width:150px; height:50px; background-color:red;">
get me!!
</div>
Why dont you use .first() of jQuery?
For example lets say you have 4 divs with same class but you want to get the text of the first div element with the specific class name:
<div class="testdiv">33</div>
<div class="testdiv">44</div>
<div class="testdiv">55</div>
<div class="testdiv">66</div>
<div class="getfirst" style="width:150px; height:50px; background-color:red;">
get me!!
</div>
$(".getfirst").click(function(){
alert($(".testdiv").first().text());
});
just added another class to the first element.

How to show a specific div when a link is clicked and hide others?

I want to show only one div when the user clicks the links on the icon bar and hide others. When the user clicks home link of the icon bar only 'hoediv'is visible and others hidden.
My work is below please help!!
<!doctype HTML>
<head>
<div class="main-header-div">
<a id="home" href="" > Home</a>
<a id="about" href=""> About us</a>
</div>
</head>
<body>
<script>
$(function(){
$("#home").click(function(){
$("#homediv").show();
$("#aboutus").hide();
return false;
});
});
</script>
<div id="homediv" style="color:white; background-color:red;height:89px;
width:100%;font-size:150%; display:none;">This is my site.
</div>
<div id="aboutus" style="display:none;">
this is about us page
</div>
</body>
</html>
What you need to fix?
Firstly, <head></head> only includes metadata, the rest should be in the <body></body>.
If you're not going to make use <a> anchor tags for hyperlinking, then pass the value href="JavaScript:Void(0);" (The void operator evaluates the given expression and then returns undefined) or better yet, don't use anchor tags better yet span or button.
You didn't import jquery.js in your html file.
You can make this a lot more effecient, but I'd suggest you learn some basic html from the widely available sources and then CSS, Jquery,etc.
Sources to refer:
https://www.w3schools.com/html/html5_intro.asp
https://www.w3schools.com/css/default.asp
https://www.w3schools.com/jquery/default.asp
$(function() {
$("#home").click(function() {
$("#homediv").show();
$("#aboutus").hide();
});
$("#about").click(function() {
$("#homediv").hide();
$("#aboutus").show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main-header-div">
<a id="home" href="JavaScript:Void(0);"> Home</a>
<a id="about" href="JavaScript:Void(0);"> About us</a>
</div>
<div id="homediv" style="color:white; background-color:red;height:89px;
width:100%;font-size:150%; display:none;">This is my site.
</div>
<div id="aboutus" style="display:none;">
this is about us page
</div>
If you want to simplify it, you can use classes and data attributes to toggle wanted content:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main-header-div">
<a class="header-link" id="home" data-toggle="homediv" href="#" > Home</a>
<a class="header-link" id="about" data-toggle="aboutus" href="#"> About us</a>
</div>
<div class="content" id="homediv" style="color:white; background-color:red;height:89px;
width:100%;font-size:150%; display:none;">
This is my site.
</div>
<div class="content" id="aboutus" style="display:none;">
this is about us page
</div>
<script>
$(document).ready(function() {
$(".header-link").click(function(){
$(".content").hide();
$("#" + $(this).attr("data-toggle")).show();
});
});
</script>

Get data from element without id or class

I am building a Chrome extension (and therefore can only use JavaScript) and I need to get the link that resides in the h2 with the heading2 class.
However, there are multiple h2 items with that class (not shown here), and I will not know what the link will point to, as it changes monthly.
In this example, the content of the header is "Think before you tweet". It will always be under another header that contains the words "Featured Topic."
What I am looking to get is the /think_before_you_tweet from the href= of that h2 item. It shows that I have already completed the topic underneath the h2, but that will not always be the case.
Here is the code for the website:
<div class="chosen_for_you_section">
<div class="internal_container">
<h2 class="section_header"><img src="/public/s360/img/360-spinner.png" class="s360LogoHeader">Featured Topic <i class="fa fa-info-circle"></i> <span class="infoTxt">Read about what to do</span></h2>
<article class="article_block masonry_item " data-article_id="431">
<div class="article_image">
<img src="/thumb/public/media/nh/images/twitter_tweet_think_before_send.png?q=&h=278" />
<i class="fa fa-check-square-o article_complete article_type_icon" title="Article"></i>
<div class="action_icons">
<span class="like "><a title="Favorite"><i class="fa fa-heart"></i></a></span>
</div>
</div>
<header>
<h2 class="heading2">Think Before You Tweet!</h2>
<div class="article_required_complete">Congratulations, you've completed this required topic.</div>
<div class="category_blocks">
<p>
Social Media
</p>
</div>
</header>
</article>
<div class="focus_items">
<div class="home_side">
<p>
<img alt="" src="" style="width: 430px; height: 422px;" /><!-- I hid the img src here because it reveals some personal information and is not important -->
</p>
<p></p>
</div>
</div>
</div>
</div>
I can use jQuery in my extension, but I do not have any back-end capabilities.
Use jQuery :contains selector:
$('h2.section_header:contains("Featured Topic") + article a')[0].href
Looks like you've gotta loop through the h2.section_header headers, see if the text matches whatever you want, and then grabs the link from the header following itself.
$('h2.section_header').each(function(index, element) {
var $element = $(element);
if ($element.text().match(/Featured Topic/i)) {
$('#result').html($element.next('article').find('h2.heading2 a').attr('href'));
}
});
#result {
border: 3px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
<div class="chosen_for_you_section">
<div class="internal_container">
<h2 class="section_header"><img src="/public/s360/img/360-spinner.png" class="s360LogoHeader">Featured Topic <i class="fa fa-info-circle"></i> <span class="infoTxt">Read about what to do</span></h2>
<article class="article_block masonry_item " data-article_id="431">
<div class="article_image">
<img src="/thumb/public/media/nh/images/twitter_tweet_think_before_send.png?q=&h=278" />
<i class="fa fa-check-square-o article_complete article_type_icon" title="Article"></i>
<div class="action_icons">
<span class="like "><a title="Favorite"><i class="fa fa-heart"></i></a></span>
</div>
</div>
<header>
<h2 class="heading2">Think Before You Tweet!</h2>
<div class="article_required_complete">Congratulations, you've completed this required topic.</div>
<div class="category_blocks">
<p>
Social Media
</p>
</div>
</header>
</article>
<div class="focus_items">
<div class="home_side">
<p>
<img alt="" src="" style="width: 430px; height: 422px;" /><!-- I hid the img src here because it reveals some personal information and is not important -->
</p>
<p></p>
</div>
</div>
</div>
</div>
with jQuery's :contains selector use this:
jQuery('h2:contains("Featured Topic") ~ article h2.heading2 a').attr('href')
try at http://jsfiddle.net/ug01a0d2/
without jQuery try to bind to class "section_header" or use a cycle with the textContent check to iterate all "h2.section_header"
If there are multiple H2 class heading2 :
$('h2[class*="heading2"] a').each(function(){
var href = $(this).attr('href');
// Do what you want with this href
});
Use XPath! The syntax is pretty, uh, unfortunate, but it's very powerful:
var result = document.evaluate('//h2[#class="section_header"]/following-sibling::article//h2[#class="heading2"]/a', document, null, XPathResult.ANY_TYPE, null );
That should select that anchor node. I'm not sure if it's available to extensions, but Chrome defines a handy helper method called $x that eliminates all that boilerplate around the query.
More information: https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript

<a> element not working properly when hiding parent?

I made this script, and despite one oddity, it works fine. It's hiding/showing the parent of div element with a class containing specific content. The problem when I press my <a> elements, that act as buttons, they "filter" the divs, but it leaves the first comment <a>? If I change the element do a <div> instead no problem, but with an <a> element it behaves weirdly? Is this just a bug or?
here is a JSFiddle: https://jsfiddle.net/g1puxhs7/2/
HTML:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<a class='viewBtn'>Published<a>
<a class='viewBtn'>Completed<a>
<a class='viewBtn'>Created<a>
<div class="orders" id="orders">
<div class="row">
<div class="status">
Completed
</div>
<a>Comment</a>
</div>
<div class="row">
<div class="status">
Completed
</div>
<a>Comment</a>
</div>
<div class="row">
<div class="status">
Completed
</div>
<a>Comment</a>
</div>
</div>
<style>
.row {
width: 200px;
margin: 10px;
background: #ccc;
padding: 4px;
}
</style>
SCRIPT:
//--Filter by Status--//
$('.viewBtn').click(function() {
var txt = $(this).text();
$('.status:contains("' + txt + '")').parent().toggle();
$(this).toggleClass('down');
});
The problem is with your links:
<a class='viewBtn'>Published<a>
<a class='viewBtn'>Completed<a>
<a class='viewBtn'>Created<a>
You have 6 opening a tags, instead of 3 opening and 3 closing tags.
This is why the browser adds closing a tags in your script in a bunch of places, one of them in your first div—and then your whole DOM tree looks different than what you want.
Your markup needed to be cleaned up. Here is your markup cleaned up. Also, i find it best to add href for you anchor tags, and then you can comment them out with #, or you can add javascript:void(0). If you use the # approach, in your JS, you can add e.preventDefault();
HTML Cleaned:
<div>
<a class='viewBtn' href="#">Published</a>
<a class='viewBtn' href="#">Completed</a>
<a class='viewBtn' href="#">Created</a>
</div>
<div class="orders" id="orders">
<div class="row">
<div class="status">
Completed
</div>
<a class="stuff" onclick="Comment">Comment</a>
</div>
<div class="row">
<div class="status">
Completed
</div>
<a class="stuff">Comment</a>
</div>
<div class="row">
<div class="status">
Completed
</div>
<a class="stuff">Comment</a>
</div>
</div>
JS with preventDefault():
$('.viewBtn').click(function(e) {
e.preventDefault();
var txt = $(this).text();
$('.status:contains("' + txt + '")').parent().toggle();
$(this).toggleClass('down');
});

Categories