I can not run my like counter in javascript.
The replacement of the empty heart with the full one works properly but the counter update no. Can someone help me? Thank you
$query2 = mysql_query("SELECT * FROM totlike WHERE id_user_like = $id_user AND id_post_like = ". $risultato['id']."");
if(mysql_num_rows($query2) ==1) {
$like='<i class="glyphicon glyphicon-heart" id="'. $risultato['id'] .'"></i>';
} else {
$like='<i class="glyphicon glyphicon-heart-empty" id="'. $risultato['id'] .'"></i>';
}
echo '<div class="list" id="list_'. $risultato['id'] .'">
<div class="panel panel-default">
<div class="btn-group pull-right postbtn">
<button type="button" class="dotbtn dropdown-toggle" data-toggle="dropdown" aria-expanded="false"> <span class="dots"></span> </button>
<ul class="dropdown-menu pull-right" role="menu">
<li>Segnala</li>
'. $delete .'
</ul>
</div>
<div class="col-md-12">
<div class="question" id="question8025"><div class="img imgLiquid imgLiquid_bgSize imgLiquid_ready" style="width: 60px; height: 60px; margin: 0px auto; background-image: url("download.jpg"); background-size: cover; background-position: center center; background-repeat: no-repeat;"><img src="download.jpg" id="questionavatar" style="display: none;"></div>
<div class="media-body">
<h4 class="media-heading">'. $risultato['username'] .'<br>
<small><i class="fa fa-clock-o"></i> Yesterday, 2:00 am</small> </h4>
<p><h4>'. $status = nl2br($risultato['post']) .'</h4></p>
<ul class="nav nav-pills pull-left ">
<li>'.$like.' '.$risultato['total_like'].'</li>
</ul>
</div>
</div>
</div>
</div>
</div>';
and then
function like(id_post, tot_like) {
$.ajax({
type: "POST",
url: '../ajax/like.php',
data:{id_post:id_post},
complete: function() {
var elem = $('#'+id_post).attr('class');
if (elem=="glyphicon glyphicon-heart") {
$('#'+id_post).removeClass('glyphicon glyphicon-heart').addClass('glyphicon glyphicon-heart-empty');
$('#'+id_post).text(tot_like - 1);
} else {
$('#'+id_post).removeClass('glyphicon glyphicon-heart-empty').addClass('glyphicon glyphicon-heart');
$('#'+id_post).text(tot_like + 1);
}
}
});
When I click the counter goes to -1 or +2
You must have a refresh after you update by clicking on +1 or -1 which you are not doing it.
Also you must do ++ or -- which will be better.
1º Get the total likes, 2º show them as you are doing till now, 3º update which the user action, 4º get again refreshing o just update DOM object with +1 or -1 but will be quite useless and there may occur some error soon or mistake.
Related
I'm working on a shopping cart function using session. I am trying to make function that update the quantity of an item in shopping cart and reload the subtotal and the cart's items list on header of the page.The function update the session and reload the subtotal but the problem is that it reload the cart's items list with the old session's information (before i updated). I want it to get the new session's information. Could you give me any ideas how to fix this? Many thanks!
I tried js setTimeout($('#cart-button').load(),2000) to delay the function to see if it can get the new session but it's still not working.
P/s: I 've just tried to put $this->ajaxReloadCart($cart->totalQty, $this->money($cart->totalPrice), $cart->items); in subOneItem() function, it works fine but the cart list is now at the subtotal div
Here is my js function:
$('#sub-1-{{$item['item']['id']}}').click(function(){
var qty = $('#qty-{{$item['item']['id']}}').val();
var int_qty = parseInt(qty);
if(int_qty > 1){
int_qty--;
$('input#qty-{{$item['item']['id']}}').val(int_qty);
$('#sub-total').load('sub-one/{{$item['item']['id']}}');
$('#cart-button').load('reload-mini');
}
if(int_qty <= 1){
int_qty = 1;
}
});
My routes
Route::get('sub-one/{id}','PageController#subOneItem');
Route::get('reload-mini','PageController#reloadMiniCart');
and my controller functions:
-ajaxReloadCart:
public function ajaxReloadCart($totalQty, $totalPrice, $items){
echo ' <button type="button" class="btn btn-default">
<a href="view-cart">
<i class="fa fa-shopping-cart fa-lg"></i>
<div class="item-number">'
.$totalQty.
'</div>
</a>
</button>';
echo '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>';
echo ' <ul class="dropdown-menu cart-items-list" id="cart-items-list">';
foreach($items as $item){
$price = $this->money($item['item']['price']);
echo ' <li>
<div class="row" style="margin-left:0; margin-top:10px;">
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
<img src="upload/product/'.$item['item']->productimg->first()->name.'" width="100" />
</div>
<div class="col-xs-8 col-sm-8 col-md-8 col-lg-8">
<div class="row">
<strong>'.$item['item']['name'].'</strong>
</div>
<div class="row">'
.$price.' X '.$item['qty'].
'</div>
</div>
</div>
</li>';
}
echo ' <li><a><strong>Subtotal:</strong> <div class="pull-right">'.$totalPrice.'</div></a></li>
<li role="separator" class="divider"></li><li>To Checkout</li></ul>';
}
-subOneItem:
public function subOneItem($id){
$product = Product::find($id);
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->subOne($product, $id);
Session::put('cart',$cart);
$totalPrice = $this->money($cart->totalPrice);
// display mini cart and total price
echo $totalPrice;
}
-reloadMiniCart:
public function reloadMiniCart(){
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$this->ajaxReloadCart($cart->totalQty, $this->money($cart->totalPrice), $cart->items);
}
Try to clear the session first before you assign the new cart values to the session
with Session::forget('cart'); or clear all session with Session::flush()
then assign the new cart info to session
in your subonitem() function after
Session::put('cart',$cart);
add Session::save();
I found other way to get the cart list reloaded but i think it's not the best way.
if you guys find any other ways, please comment below. I want to find a better way.
my solution:
reload cart list every 1s
setInterval(function(){
$('#cart-button').load('reload-mini');
},1000);
I'm fetching data using for loop and echo results on a page. How do I output the results in a slider effect?
I have tried a simple CSS slider but can't get the intended result. What I end up getting is everything output in page and no sliding effect.
Part of my PHP code that echo the output...
for ($i=0, $n=count($rows); $i < $n; $i++) {
//echo "<tr><td>".
($row = $rows[$i]);
//."</td></tr>";
$link_detail = JRoute::_('index.php?option=com_jblance&view=user&layout=viewprofile&id='.$row->user_id.$Itemid);
$link_invite = JRoute::_('index.php?option=com_jblance&view=project&layout=invitetoproject&id='.$row->user_id.'&tmpl=component');
?>
<div class="slider">
<div class="media style_prevu_kit">
<div class="center">
<?php
if($show_logo){
$link = LinkHelper::GetProfileLink($row->user_id, $row->$nameOrUsername);
$attrib = 'style="width: 162px; height: 162px; float:center; margin: 0 auto; border-radius: 100px"';
//echo JblanceHelper::getLogo($row->user_id, $attrib);
echo "<a href='".$link_detail."' class='link'>".JblanceHelper::getLogo($row->user_id, $attrib)."</a>";
//echo $link_detail;
} ?>
</div>
<div class="media-body">
<h5><?php //$username = LinkHelper::GetProfileLink($row->user_id, $row->$nameOrUsername);
$getUsername = $row->$nameOrUsername;
$nameorUsername = truncate($getUsername, 5);
echo LinkHelper::GetProfileLink($row->user_id, $nameorUsername);
//echo truncate($username, 15);
?></h5>
<?php //<?php echo JblanceHelper::getCategoryNames($row->id_category, 'tags-link', 'user'); ?>
</span>
<br /><br />
</div>
<div class="center">
<input type="button" value="Hire Me" class="button_add button_curved_blue color-a">
</div>
<div class="lineseparator"></div>
<div class="container">
<div class="content">
<div class="grid-2">
<button class="color-b circule"> <i class="fab fa-dribbble fa-2x"></i></button>
<h6 class="title-2">12.3k</h6>
<p class="followers">Followers</p>
</div>
<div class="grid-2">
<button class="color-c circule"><i class="fab fa-behance fa-2x"></i></button>
<h6 class="title-2">16k</h6>
<p class="followers">Followers</p>
</div>
<div class="grid-2">
<button class="color-d circule"><i class="fab fa-github-alt fa-2x"></i></button>
<h6 class="title-2">17.8k</h6>
<p class="followers">Followers</p>
</div>
</div>
</div>
</div>
</div>
<?php
}
A very simple slider CSS...
.slider {
white-space: nowrap;
oveflow:hidden;
}
.slider>div {
white-space: normal; /* reset "nowrap" above */
display: inline-block;
transition: margin-left 0.8s cubic-bezier(0.5, 0.1, 0.5, 1.25);
/* the above transition gives a neat little "bounce-back" effect */
}
And 1 line of JavaScript...
<script>
theSlider.children[0].style.marginLeft = (-100*pageID)+"%";
</script>
What I get now is this...
While I need all 8 cards to automatically be sliding in 1 row or to have previous and next buttons to transition between the cards
I have a page with some billing info. I want to affect a div based on the values of other divs. But, there is no output in my desired div.
Below is what I have so far:
$(document).ready(function () {
$(".content-wrapper.planwrapper").each(function() {
var originalRate = $(this).find(".v-ratePlanValue").text().replace("¢","");
var newBill = eval(originalRate*500+5.95);
});
$(this).find(".estimatedbill-wrapper .term-description").replace($(this),'$newBill');
});
I'm pretty new to JS, so any help would be appreciated!
Edit: Here is the HTML for one of the divs I'm working with -
<div class="esco_electric">
<div class="esco_lower-wrapper">
<div class="esco_rates-list" id="electric_list">
<div class="rate-item row-id-Electric-' . $oneplan->ProductId . '-' . $oneplan->UtilityID . ' color3" data-product-id="' . $oneplan->ProductId . '" data-utility-id="' . $oneplan->UtilityID . '" data-tpv-id="' . $oneplan->TPVTemplateID . '" data-utility-name="' . $oneplan->UtilityShortName . '" data-zone="">
<!-- Price / Suffix / Plan Type -->
<div class="rate-type rate-wrapper">
<div class="rate-price" style="position:relative;">
<div class="mobleft" style="margin-bottom: 0px;">Fixed Rate</div>
<div id="pricediv-Electric-1853-50" class="price v-ratePlanValue mobcenter" style="padding-top:5px;">7.4<span style="font-size:0.7em;">¢</span></div>
<div class="price-suffix v-rateMeasurementSuffix mobright">kWh </div>
</div>
</div>
<!-- Description Area -->
<div class="rate-description description-wrapper">
<!-- Upper Description -->
<div class="description-text">
<div class="term-title">Term</div>
<div class="term-description">
6 Months </div>
<div class="description-contentpricediv-Electric-1853-50 v-ratePlanDescription">No Cancellation Fee </div>
</div>
</div>
<div class="rate-description estimatedbill-wrapper">
<div class="description-text">
<div class="estimatedbill-title">Estimated Bill</div>
<div class="term-description">
$148 </div>
<div class="v-ratePlanDescription howisthiscalculated" data-mfp-src="#howisthiscalculated-popover">
How is this calculated?
</div>
</div>
</div>
<style>
.description-contentpricediv-Electric-1853-50 {
margin-top: 19px;
text-align: center;
font-size: 16px !important;
color: #535353!important;
}
</style>
<!-- Action buttons -->
<a id="selectrateid-Electric-1853-50" href="index.php?type=resi&s=options_and_information&plan=1853&StartDate=12-May-2016">
<div class="selectplan">
<p>Select Plan</p>
</div>
</a>
<a class="rate-edit" href="#">
<img src="images/check.png">
<p>
Edit Plan
</p>
</a>
</div>
<!-- end rateitem -->
<div id="UDSDIVID-Electric-1853-50" data-alert="" class="alert-box radius infodiv">
<div class="pdfdiv">
<a eslinktext="Datos de la Electricidad" eslinkurl="PDFTemplates/ResidentialContracts/EFLViewer.php?lang=es&key=RW5lcmd5Q2hhcmdlPTQuMSZQbGFuTmFtZT1UaGluayBTZWN1cmUgNiZJc3N1ZURhdGU9MDUvMTIvMjAxNiZVdGlsaXR5U2hvcnROYW1lPU9OQ09SJnByb2R1Y3R0ZXJtPTYmdGVybWZlZT0w" class="pdfcustom" href="PDFTemplates/ResidentialContracts/EFLViewer.php?key=RW5lcmd5Q2hhcmdlPTQuMSZQbGFuTmFtZT1UaGluayBTZWN1cmUgNiZJc3N1ZURhdGU9MDUvMTIvMjAxNiZVdGlsaXR5U2hvcnROYW1lPU9OQ09SJnByb2R1Y3R0ZXJtPTYmdGVybWZlZT0w" target="_blank" style="color:#000000;"><img src="images/pdf.png" height="25" width="25"> Electricity Facts Label</a><br>
<a eslinktext="Terminos y Condiciones" eslinkurl="PDFTemplates/TermsofServices/TOS_TX_Spanish.pdf?key=c3RhdGU9VFgmcmF0ZT00LjEmdGVybT02JnBsYW5uYW1lPVRoaW5rIFNlY3VyZSA2" class="pdfcustom" href="PDFTemplates/contract_api/index.php/contract/TC/state/TX/customer_type/RESI/service/Electric?PlanName=Think+Secure+6&ContractNumber=TBD&ServiceAddress=&Price=4.1&ServiceCity=&ServiceAddress2=&ServiceState=&ServiceZipCode=&Term=6&MonthEnding=November&Timestamp=1463061182 " target="_blank" style="color:#000000;"><img src="images/pdf.png" height="25" width="25"> Terms of Service</a><br>
<a eslinktext="Sus Derechos como Cliente" eslinkurl="PDFTemplates/Contracts/TX_YRAC_Spanish.pdf" class="pdfcustom" href="PDFTemplates/Contracts/TX_YRAC.pdf" target="_blank" style="color:#000000;"><img src="images/pdf.png" height="25" width="25"> Your Rights as a Customer</a><br><br>
</div>
<!-- end pdfdiv-->
<div class="textrightdiv">Please contact Customer Care to request that a written copy of the terms of service document be sent to you by regular U.S. mail.<br><br><span style="padding-right: 30px;">Email Request: </span>customercare#mythinkenergy.com<br><span style="padding-right: 25px;">Phone Request: </span>1-888-238-5610<br><a class="small button spanishButton" name="btnshowspanish" id="btnshowspanish22422" onclick="showspanishcontracts('btnshowspanish22422');">Documentos en Español</a></div><a onclick="$('#UDSDIVID-Electric-1853-50').hide();" style="display: none; padding: 10px;color:#000000;cursor: pointer; cursor: hand;position: absolute;top: 10px; right: 10px;">X</a>
<div style="clear: both;"></div>
</div>
</div>
</div>
</div>
Your logic is correct, while your code is incorrect, there are several mistakes that needs to be fixed:
There's no need to use eval, it has no effect in your code and it's better to avoid its use.
To use the variable newBill you don't need to write $newBill and
if you put it inside '' it will be interpreted as string and simply printthe sentence$newBill`.
And in your case you declared the variable newBill inside .each function so it will be undefined outside this function scope so you can't use it outside of it, you need to declare it outside it.
And the use of $(".content-wrapper.planwrapper").each(function() { is unnecessary in your case and will break your code.
And You are using .replace() in the wrong place, to change the
content of a div use .text(content) and not .replace().
This is how should be your code:
$(document).ready(function() {
var newBill = 0;
var originalRate = $(this).find(".v-ratePlanValue").text().replace("¢", "");
newBill = parseFloat(originalRate) * 500 + 5.95;
$(this).find(".estimatedbill-wrapper .term-description").text(newBill);
});
THis is a working DEMO:
$(document).ready(function() {
var newBill = 0;
var originalRate = $(this).find(".v-ratePlanValue").text().replace("¢", "");
newBill = parseFloat(originalRate) * 500 + 5.95;
$(this).find(".estimatedbill-wrapper .term-description").text(newBill);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="esco_electric
">
<div class="esco_lower-wrapper">
<div class="esco_rates-list" id="electric_list">
<div class="rate-item row-id-Electric-' . $oneplan->ProductId . '-' . $oneplan->UtilityID . ' color3" data-product-id="' . $oneplan->ProductId . '" data-utility-id="' . $oneplan->UtilityID . '" data-tpv-id="' . $oneplan->TPVTemplateID . '" data-utility-name="' . $oneplan->UtilityShortName . '"
data-zone="">
<!-- Price / Suffix / Plan Type -->
<div class="rate-type rate-wrapper">
<div class="rate-price" style="position:relative;">
<div class="mobleft" style="margin-bottom: 0px;">Fixed Rate</div>
<div id="pricediv-Electric-1853-50" class="price v-ratePlanValue mobcenter" style="padding-top:5px;">7.4<span style="font-size:0.7em;">¢</span>
</div>
<div class="price-suffix v-rateMeasurementSuffix mobright">
kWh</div>
</div>
</div>
<!-- Description Area -->
<div class="rate-description description-wrapper">
<!-- Upper Description -->
<div class="description-text">
<div class="term-title">Term</div>
<div class="term-description">
6 Months</div>
<div class="description-contentpricediv-Electric-1853-50 v-ratePlanDescription">
No Cancellation Fee</div>
</div>
</div>
<div class="rate-description estimatedbill-wrapper">
<div class="description-text">
<div class="estimatedbill-title">Estimated Bill</div>
<div class="term-description">
$148</div>
<div class="v-ratePlanDescription howisthiscalculated" data-mfp-src="#howisthiscalculated-popover">
How is this calculated?
</div>
</div>
</div>
<style>
.description-contentpricediv-Electric-1853-50 {
margin-top: 19px;
text-align: center;
font-size: 16px !important;
color: #535353!important;
}
</style>
<!-- Action buttons -->
<a id="selectrateid-Electric-1853-50" href="index.php?type=resi&s=options_and_information&plan=1853&StartDate=12-May-2016">
<div class="selectplan">
<p>Select Plan</p>
</div>
</a>
<a class="rate-edit" href="#">
<img src="images/check.png">
<p>
Edit Plan
</p>
</a>
</div>
<!-- end rateitem -->
<div id="UDSDIVID-Electric-1853-50" data-alert="" class="alert-box radius infodiv">
<div class="pdfdiv">
<a eslinktext="Datos de la Electricidad" eslinkurl="PDFTemplates/ResidentialContracts/EFLViewer.php?lang=es&key=RW5lcmd5Q2hhcmdlPTQuMSZQbGFuTmFtZT1UaGluayBTZWN1cmUgNiZJc3N1ZURhdGU9MDUvMTIvMjAxNiZVdGlsaXR5U2hvcnROYW1lPU9OQ09SJnByb2R1Y3R0ZXJtPTYmdGVybWZlZT0w"
class="pdfcustom" href="PDFTemplates/ResidentialContracts/EFLViewer.php?key=RW5lcmd5Q2hhcmdlPTQuMSZQbGFuTmFtZT1UaGluayBTZWN1cmUgNiZJc3N1ZURhdGU9MDUvMTIvMjAxNiZVdGlsaXR5U2hvcnROYW1lPU9OQ09SJnByb2R1Y3R0ZXJtPTYmdGVybWZlZT0w" target="_blank" style="color:#000000;">
<img src="images/pdf.png" height="25" width="25">Electricity Facts Label</a>
<br>
<a eslinktext="Terminos y Condiciones" eslinkurl="PDFTemplates/TermsofServices/TOS_TX_Spanish.pdf?key=c3RhdGU9VFgmcmF0ZT00LjEmdGVybT02JnBsYW5uYW1lPVRoaW5rIFNlY3VyZSA2" class="pdfcustom" href="PDFTemplates/contract_api/index.php/contract/TC/state/TX/customer_type/RESI/service/Electric?PlanName=Think+Secure+6&ContractNumber=TBD&ServiceAddress=&Price=4.1&ServiceCity=&ServiceAddress2=&ServiceState=&ServiceZipCode=&Term=6&MonthEnding=November&Timestamp=1463061182 "
target="_blank" style="color:#000000;">
<img src="images/pdf.png" height="25" width="25">Terms of Service</a>
<br>
<a eslinktext="Sus Derechos como Cliente" eslinkurl="PDFTemplates/Contracts/TX_YRAC_Spanish.pdf" class="pdfcustom" href="PDFTemplates/Contracts/TX_YRAC.pdf" target="_blank" style="color:#000000;">
<img src="images/pdf.png" height="25" width="25">Your Rights as a Customer</a>
<br>
<br>
</div>
<!-- end pdfdiv-->
<div class="textrightdiv">Please contact Customer Care to request that a written copy of the terms of service document be sent to you by regular U.S. mail.
<br>
<br><span style="padding-right: 30px;">Email Request: </span>customercare#mythinkenergy.com
<br><span style="padding-right: 25px;">Phone Request: </span>1-888-238-5610
<br><a class="small button spanishButton" name="btnshowspanish" id="btnshowspanish22422" onclick="showspanishcontracts('btnshowspanish22422');">Documentos en Español</a>
</div><a onclick="$('#UDSDIVID-Electric-1853-50').hide();" style="display: none; padding: 10px;color:#000000;cursor: pointer; cursor: hand;position: absolute;top: 10px; right: 10px;">X</a>
<div style="clear: both;"></div>
</div>
</div>
</div>
</div>
Check it out: https://jsfiddle.net/vmtzqnu0/5/
There are a few things to fix to get this working:
1. Your use of var
This keyword creates a variable within the code block (scope) that you use it, but outside of that block it's no longer usable. So when you say var newBill = ... inside the $.each() loop, you can't use it outside of there.
We can fix this by removing the keyword and (optionally) add the var newBill; statement just outside that block:
$(document).ready(function () {
var newBill; // will be used later
$(".content-wrapper.planwrapper").each(function() {
var originalRate = $(this).find(".v-ratePlanValue").text().replace("¢","");
newBill = eval(originalRate*500+5.95);
});
$(this).find(".estimatedbill-wrapper .term-description").replace($(this),'$newBill');
});
2. Your use of eval()
You should probably just never use eval(). Moreover, it doesn't do what you think. You pass it a string of JS code and it will run that code. You don't pass it a statement.
So newBill = eval(originalRate*500+5.95); becomes newBill = originalRate*500+5.95;. You're best off wrapping that in parseFloat() too:
newBill = parseFloat(originalRate) * 500 + 5.95;
3. Your use of $.replace()
Here you actually want to use $.text() or $.html(). These functions are used to replace the content of an element. So, your final code will look like this:
$(document).ready(function() {
var newBill;
$(".content-wrapper.planwrapper").each(function() {
var originalRate = $(this).find(".v-ratePlanValue").text().replace("¢", "");
newBill = parseFloat(originalRate) * 500 + 5.95;
});
$(this).find(".estimatedbill-wrapper .term-description").text(newBill)
});
4. There is no .planwrapper
Instead, loop through .v-ratePlanValue:
$(document).ready(function() {
var newBill;
$(".v-ratePlanValue").each(function() {
var originalRate = $(this).text().replace("¢", "");
console.log(this, originalRate);
newBill = '$' + ((parseFloat(originalRate) * 500) + 5.95);
});
$(this).find(".estimatedbill-wrapper .term-description").text(newBill)
});
Good resources while learning Javascript, jQuery:
MDN JS Tutorial
jQuery Documentation
JS Debugging Guide
I have a little problem. Im trying to create my own slider using jQuery and some css/javascript.
I got my slider to work moving a Div 660px to the left and right by clicking a button.
But, I would like to have the right button disabled when the left margin is 0. And I would like the whole div to rewind back to 0px after some clicks.
Is this possible?
Here is my code:
<script language="javascript">
function example_animate(px) {
$('#slide').animate({
'marginLeft' : px
});
}
</script>
<div class="container">
<div class="row">
<div class="contr-left">
<a type="button" value="Move Left" onclick="example_animate('-=600px')"><i class="fa fa-chevron-circle-left fa-2x" aria-hidden="true" ></i></a>
</div>
<div id="carreview" class="carousel" data-ride="carousel" style="opacity: 1; display: block;">
<div class="wrapper-outer">
<div class="wrapper-inner" id="slide">
<?php get_template_part('loop-reviews');?>
</div>
</div>
<div class="contr-right">
<a type="button" value="Move Right" onclick="example_animate('+=600px')"><i class="fa fa-chevron-circle-right fa-2x" aria-hidden="true" ></i></a>
</div>
</div>
</div>
</div>
The code im using is from this page: Page
Well, with the code from Rayn i got the button to hide, but now it won't show when left-margin is 1px or something. So I'm trying this now: (doesn't work btw)
Im trying this now: (doesn't work btw)`function example_animate(px) {
$('#slide').animate({
'marginLeft' : px
});
var slidemarginleft = $('#slide').css('margin-left'); //this gets the value of margin-left
if(slidemarginleft == '0px'){
$('.contr-right').hide();
} else (slidemarginleft == '1px') {
$('.contr-right').show();
}
}`
Also I'm seeing that the margin-left isn't set in the style sheet but in the
<div style="margin-left:0px">content</div>
You can do an if statement after each click to check if the element has 0px
function example_animate(px) {
$('#slide').animate({
'marginLeft' : px
});
var slidemarginleft = $('#slide').css('margin-left'); //this gets the value of margin-left
if(slidemarginleft == '0px'){
$('.contr-right').hide();
}
}
Use this
function example_animate(px) {
$('#slide').animate({
'marginLeft' : px
});
if($('.xman').css("marginLeft")=='0px'){
$('.contr-left').attr('disabled',true);
}
}
Disable Button when margin-left: 0px
You can use jquery's .prop() method to disable a button if a condition is met. Here is an example (in pseudo code):
function disableButton() {
$(element).prop('disabled', true);
}
function checkMargin() {
if ($(element).css("margin") === 0) {
disableButton()
}
}
checkMargin()
Rewind to 0px after some clicks
Here, I'd just set a count for clicks and trigger a function when it meets the threshold you want. Pseudo code:
var threshold = 5
var clicks = 0
$(element).click(function(){
clicks++
if (clicks === 5) {
rewind();
}
clicks - 5
})
function rewind() {
$(element).css( "margin", "0" );
checkMargin()
}
Here is my working code, thanks for all the help:
<script>
function example_animate(px) {
$('#slide').animate({
'marginLeft' : px
});
var slidemarginleft = $('#slide').css('margin-left'); //this gets the value of margin-left
if(slidemarginleft < '-3000px'){
$('#slide').animate({marginLeft: '0px'}, 400);
}
var hide = $('#slide').css('margin-left'); //this gets the value of margin-left
if(hide >= '-50px'){
$('.contr-left').addClass('showMe');
}
var hideMe = $('#slide').css('margin-left'); //this gets the value of margin-left
if(hideMe <= '-50px'){
$('.contr-left').removeClass('showMe');
}
}
</script>
<!-- /Review script -->
<section id="reviews">
<div class="container">
<div class="row">
<div class="container">
<div class="row">
<h4>Reviews</h4>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-sm-1" style="width:40px;">
<div class="row">
<div class="contr-left">
<a type="button" value="Move Left" onclick="example_animate('+=510px')"><i class="fa fa-chevron-circle-left fa-2x" aria-hidden="true" ></i></a>
</div>
</div>
</div>
<div class="col-sm-10">
<div class="row">
<div id="carreview" class="carousel" data-ride="carousel" style="opacity: 1; display: block;">
<div class="wrapper-outer">
<div class="wrapper-inner" id="slide" style="margin-left:0px;">
<?php get_template_part('loop-reviews');?>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-1" style="width:40px;">
<div class="row">
<div class="contr-right">
<a type="button" value="Move Right" onclick="example_animate('-=510px')"><i class="fa fa-chevron-circle-right fa-2x" aria-hidden="true" ></i></a>
</div>
</div>
</div>
</div>
<div class="btn btn-06">Bekijk alle reviews</div>
</div>
</section>
So i will try to explain bit more into detail.
So I've got a gallery with 9 elements floated left creating 3 elements per line like this:
1 2 3 <--line 1
4 5 6 <--line 2
7 8 9 <--line 3
What i am trying to do is when i click on either element i want to add a div bellow the line its part of. For example if i click on element 2 it should add a div after the 3rd element between line 1 and 2.
I tried selecting all the 3rd elements of the line (using :nth-child) but i cant make jquery understand on which line it is.
To be honest i am really confused about how to approach this.
Any ideas would be tremendously helpful.
Thank you.
Constantin Chirila
Later edit:
The code is a mess and its part of a bigger thing so sorry for that.
<a href="#" class="dealer--item" data="hongkong">
<h4 class="dealer--item-title">Hong Kong</h4>
</a>
<a href="#" class="dealer--item" data="australia">
<h4 class="dealer--item-title">Sweden</h4>
</a>
<a href="#" class="dealer--item" data="sweden">
<h4 class="dealer--item-title">Sweden</h4>
</a>
<a href="#" class="dealer--item" data="uk">
<h4 class="dealer--item-title">United kingdom</h4>
</a>
<a href="#" class="dealer--item" data="germany">
<h4 class="dealer--item-title">Germany</h4>
</a>
<a href="#" class="dealer--item" data="netherlands">
<h4 class="dealer--item-title">The Netherlands</h4>
</a>
<a href="#" class="dealer--item" data="canada">
<h4 class="dealer--item-title">Canada</h4>
</a>
<a href="#" class="dealer--item" data="malaysia">
<h4 class="dealer--item-title">Malaysia</h4>
</a>
<a href="#" class="dealer--item" data="thailand">
<h4 class="dealer--item-title">Thailand</h4>
</a>
<a href="#" class="dealer--item" data="japan">
<h4 class="dealer--item-title">Japan</h4>
</a>
<a href="#" class="dealer--item" data="korea">
<h4 class="dealer--item-title">Korea</h4>
</a>
<a href="#" class="dealer--item" data="indonesia">
<h4 class="dealer--item-title">Indonesia</h4>
</a>
<a href="#" class="dealer--item" data="taiwan">
<h4 class="dealer--item-title">Taiwan</h4>
</a>
</div>
Jquery:
$(".dealer--item").click(function (e) {
var idSelector = $(this).attr('data');
e.preventDefault();
$('.dealer--item').not(this).removeClass('is-selected');
$(this).toggleClass("is-selected");
$(".dealer--item:nth-child(3n)").each(function (index) {
$(this).addClass("foo" + index);
});
$('foo0').after($('#' + idSelector)) //this is where i lost it as its not working for other 6 elements
$('#' + idSelector).fadeToggle(300);
});
And content that needs to be added between the lines based on the element clicked.
<div class="dealer--address" id="australia">
Address here
</div>
<div class="dealer--address" id="hongkong">
Address here
</div>
<div class="dealer--address" id="sweden">
Address here
</div>
<div class="dealer--address" id="uk">
Address here
</div>
<div class="dealer--address" id="germany">
Address here
</div>
etc...
Have you considered adding an extra div below the floated left elements and just hiding them initially with display:none; and then using jQuery to show them using the on click function.
$("#clickable element").click(function(){
$("element to show").show();
});
This is the way I do all of my click and display behaviors with jQuery.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<style type="text/css">
.floating {
float: left;
width: 30%;
margin: 1%;
height: 100px;
background: #ffe4c4;
}
.Content {
display:none;
width: 100%;
background: green;
}
#contentOnDisplay {
min-height: 100px;
width: 100%;
float: left;
background: green;
display: block;
}
</style>
</head>
<body>
<div class="Content" id="floating1Content">content for 1</div>
<div class="Content" id="floating2Content">content for 2</div>
<div class="Content" id="floating3Content">content for 3</div>
<div class="Content" id="floating4Content">content for 4</div>
<div class="Content" id="floating5Content">content for 5</div>
<div class="Content" id="floating6Content">content for 6</div>
<div class="Content" id="floating7Content">content for 7</div>
<!-- <div class="Content" id="floating8Content">content for 8</div>
<div class="Content" id="floating9Content">content for 9</div>-->
<div class="floating" id="floating1"></div>
<div class="floating" id="floating2"></div>
<div class="floating" id="floating3"></div>
<div class="floating" id="floating4"></div>
<div class="floating" id="floating5"></div>
<div class="floating" id="floating6"></div>
<div class="floating" id="floating7"></div>
<!-- <div class="floating" id="floating8"></div>
<div class="floating" id="floating9"></div>-->
<script type="text/javascript">
var getLeftMostPositionOfFirstItem = $("#floating1").position().left;
$(document).ready(function() {
$(".floating").click(function() {
var elementID = $(this).attr("id");
$("#contentOnDisplay").remove(); //hides the existing contents
var firstItemOFNextRow = getTheFirstItemOfNextRow(elementID);
getAllTheConstentsOfAdivAndPrepenedIt(firstItemOFNextRow, getTheIdOfFirstItemOfNextRow(elementID));
return false;
});
});
function getTheFirstItemOfNextRow(clickedItemID) {
var getTheIdNumberOfThisItem = parseInt(clickedItemID.replace("floating", ""));
var position = $("#" + clickedItemID).position();
var idOfTheElementToBeInstertedBefore = "";
for (var i = getTheIdNumberOfThisItem + 1; i < $(".floating").length; i++) {
var leftPostitonOfThisItem = $("#floating" + i).position().left;
if (leftPostitonOfThisItem < getLeftMostPositionOfFirstItem*1.5) {
idOfTheElementToBeInstertedBefore = "#floating" + i;
break;
}
}
if (idOfTheElementToBeInstertedBefore.length == "") {
idOfTheElementToBeInstertedBefore = "#floating" + $(".floating").length;
}
return idOfTheElementToBeInstertedBefore;
};
function getTheIdOfFirstItemOfNextRow(elementID) {
return parseInt(elementID.replace("floating", ""));
};
function getAllTheConstentsOfAdivAndPrepenedIt(idToPrepend, IdNumber) {
var htmlOfTheContent = $("#floating" + IdNumber + "Content").html();
htmlOfTheContent = "<div id='contentOnDisplay'>" + htmlOfTheContent + "</div>";
if (IdNumber <= $(".floating").length - getNuumberOfItemsInLastRow()) {
$(idToPrepend).before(htmlOfTheContent);
} else {
$(idToPrepend).after(htmlOfTheContent);
}
return false;
};
function getNuumberOfItemsInLastRow() {
var numberOfColoumns = 0;
for (var i = $(".floating").length; i > 0; i--) {
var leftPostitonOfThisItem = $("#floating" + i).position().left;
numberOfColoumns++;
if (leftPostitonOfThisItem < getLeftMostPositionOfFirstItem * 1.5) {
break;
}
}
return numberOfColoumns;
};
</script>
</body>
</html>