I have a page that displays a table with numbers. These are the prices my partner sees in the store. This page is specially made for him.
Prices change often. I enter prices in WordPress. I created Custom Post Type and a simple form to enter these numbers. One price = one custom field. The number of fields is around 30.
And it works great. But I need to detect the price change.
I would like the site for my partner clearly show the price change.
The ideal situation is when the DIV with new price has a changed color, and next to it appears a button to reset its color.
Such a mechanism will allow you to quickly find out about price changes.
This page is refreshed every 10 seconds.
I know the basics of JS, but I do not know how to do it. I suspect you will need to use SessionStorage.
Can anyone give me directions or paste a link to similar solution?
I have a lot of divs such as:
<div id="price1">[types field='price1'][/types]</div>
and JS:
setTimeout(function(){
window.location.reload(1);
}, 10000);
var price1 = document.getElementById('price1').textContent;
sessionStorage.setItem("price1-box", "price1");
var handle_storage = function () {
console.log('change in storage! new' + price1);
};
window.addEventListener("storage", handle_storage, false);
I made o solution. Maybe it will be useful to someone else.
<div id="eur-k">123</div>
window.onload = function() {
setTimeout(function(){
window.location.reload(1);
}, 30000);
// define div to add or remove alert
var eurkDiv = document.getElementById('eur-k');
// store current content in a variable
var eurk = eurkDiv.textContent;
// compare local storage with current content to make alarm
if (localStorage.getItem('eurkLoc') != eurk) {
eurkDiv.classList.add("active");
eurkDiv.innerHTML = eurk + "<button type=\"button\" class=\"potwierdzenie\" onclick=\"resetFunction()\">OK</button>";
}
function resetFunction() {
eurkDiv.classList.remove("active");
eurkDiv.textContent = eurk;
localStorage.setItem('eurkLoc', eurk);
};
};
Related
Today, I was thinking if a javascript is possible to replace an element after refreshing the page 10 times specifically. I would really need this to replace an element after amount of page refreshes to make it static. I was trying to code it but all, I coded so far is to replace it after clicking on the element 3 times. And localStorage logs it and creates a key so the webserver remembers the change. All, I want is the element to replace its code with urls code after 10 refreshes on the page.
var count = parseInt(localStorage.getItem("count"), 10) || 0;
function loadMyPage() {
if (count >= 3)
$("#id-2").load("yoinkexecutor2.html");
}
}
$(document).ready( function () {
loadMyPage();
$("#id-2").on("click", function() {
localStorage.setItem("count", count += 1);
loadMyPage();
});
});
Ok, I updated the fiddle to work when the fiddle is reloaded. Don't worry too much about my mockHtmlReq function as it's just to mock a request for HTML content, similar to .load().
The only thing I changed was inside the $(document).ready()
$(document).ready( function () {
loadMyPage();
localStorage.setItem("count", count += 1);
});
Basically what happens is everytime the page reloads we are just incrementing up our count value stored in localStorage.
Question:
How can I show the number of items in a user's cart using the minicart.js script?
Backstory:
I'm developing a static HTML website that is selling a small number of products using standard PayPal buttons and minicart.js
I'd like to have an area in the header of my website that displays the number of items currently in the "cart", but I can't figure out how to do so. There is no example detailing this functionality on the minicart.js website.
I'm sure it can be done, but I'm at a loss. Any help would be greatly appreciated. Thanks!
You can get like this:
paypal.minicart.cart.items().length
It works for me
I managed to figure out a way to achieve what I'm looking for by finding the necessary variable set through minicart.js and then manipulating it via jQuery.
minicart.js gives me the following variable which outputs the current cart total:
paypal.minicart.cart.total();
I then took that variable and applied some jQuery that converted this variable into a separate variable called "cartTotal" which is checked and updated every time a user interaction happens on the page (ie - a click or a keypress). I found that a brief delay was needed in order for everything to work properly. Interestingly, the keypress check needs a longer delay than the mouse click.
My final (for now) working code is as follows:
$( document ).ready(function() {
var cartTotal = paypal.minicart.cart.total();
$('input#cart').val('$' + cartTotal);
$( "body" ).click(function() {
setTimeout(function() { // Setting slight delay on function to accomodate for button push of removing items from cart
var cartTotal = paypal.minicart.cart.total();
$('input#cart').val('$' + cartTotal);
}, 100);
});
$( "body" ).keypress(function() {
setTimeout(function() { // Setting longer delay on function to accomodate for key push of removing items from cart
var cartTotal = paypal.minicart.cart.total();
$('input#cart').val('$' + cartTotal);
}, 900);
});
What I am looking for is slightly subjective, but I am sure there is a better way to do this.
I am looking for a better way to perform javascript while a user is typing content into either a textarea or input box on a website. For instance, sites such as Google Docs are capable of saving changes to documents almost instantly without noticeable performance degradation. Many sites however use a bit of jQuery that might look like the following:
$("#element").on("keyup", function() { /* Do something */ });
This works fine for simple things like autocomplete in search boxes, but performance becomes a nightmare once you have any sizable corpus for it to have to deal with (or if a user types fast, yikes).
In trying to find a better way to analyze/save/what-have-you text as the user is typing, I started to do something like this:
var changed = false;
$("#element").on("keyup", function() { changed = true });
setInterval(function() { if(changed) { /* Do something */ changed = false; } }, 1000);
It seems to alleviate laggy or delayed text input, but to me it seems like a less than elegant solution.
So back to my question, is there a better way to have javascript execute when a corpus has been changed? Is there a solution outside of using intervals?
Thanks.
There is a jQuery plugin that does pretty much what you did.
Your example will be transformed into
$("#element").on("keyup", $.debounce(1000, function() { /* Do something */ }));
The code will execute after a user is not pressing any keys for 1000ms.
I have found a very good solution for this. This code will check whether the content has been changed and based on that it will save it otherwise the save functionality will not be executed !
Check out this demo JSFIDDLE
Here is the code :
HTML :
Content:<br>
<br>
(type some text into the textarea and it will get saved automatically)
<textarea rows="5" cols="25" id="content"></textarea>
<br>
<span id="sp_msg_saved" style="background-color:yellow; display:none">Content is saved as draft !</span>
JS:
var old_content = "";
function save_content()
{
var current_content = $('#content').val();
//check if content has been updated or not
if(current_content != old_content)
{
alert('content is updated ! Save via ajax');
old_content = current_content;
$('#sp_msg_saved').show(100);
$('#sp_msg_saved').fadeOut(3000);
}
}
setInterval(save_content,3000);
You can increase or decrease the amount of time for the save function to call by altering the values in setInterval function. Put the code for saving the content via ajax, that will save the current user content into your DB, I haven't included that one...
You can make your own little delay by using the window.setTimeout-Function:
var IntervalId = null;
function saveEdits(){
//Doing your savings...
}
$('input').keyup(function(){
if (IntervalId){
window.clearTimeout(IntervalId);
IntervalId = null;
}
IntervalId = window.setTimeout(function(){
saveEdits();
}, 3000);
});
Here is a link to my code: http://www.canning.co.nz/Mapping/Code.txt
Sorry, it is in text format, for some reason I had some trouble in pasting it into this forum.
It is working nicely. However, I am after a little bit of help with a problem that I am having. Currently, the textboxes come up for the start and destination after I click on a button. I am wanting to have these textboxes all display when the page loads and then just press on the button and the route will be displayed.
Can I please have some help with this? Or is there a better example that I can have a look at somewhere on the net?
thanks
You can adapt your current example to work this way. First you need a couple more JavaScript functions. You can place these below the directions() function.
JavaScript:
function searchFunc(point) {
if (point) {
if (state==1) {doEnd(point)}
if (state==0) {doStart(point)}
} else {
var result=geo.getCache().get(search);
if (result) {
var reason="Code "+result.Status.code;
if (reasons[result.Status.code]) {
reason = reasons[result.Status.code]
}
} else {
var reason = "";
}
alert('Could not find "'+search+ '" ' + reason);
}
}
function GLoad() {
var search = document.getElementById("search").value,
search2 = document.getElementById("search2").value;
addresses[0] = search;
addresses[4] = search2;
geo.getLatLng(search, searchFunc);
geo.getLatLng(search2, searchFunc);
}
Next you need to remove the three calls to handleState(). There is one call right below the function declaration. The other two are in doStart() and doEnd(). You can also remove the function itself. This function was doing the show/hide of the fields and buttons.
Finally, you need to update the tag to call GLoad().
<body onload="GLoad()" onunload="GUnload()">
Now if you click Get Directions the page should function the same as before, except we've taken care of the first couple button clicks and all the fields remain visible.
You probably want to also remove the buttons for "Find start address" and "Find destination address" but I wasn't sure. Removing them is as simple as removing the buttons from the HTML.
Feel free to ask any questions. I hope that helps!
A quick thank you to those that have helped me so far with this script, you have all helped me enormously in learning some of the more elegant sides of javascript and jquery.
I have one final problem with this script, I am using setinterval() to cycle through an image changer, the JS/Jquerycode is as follows:
$(function() {
var rotateTimer = setInterval(rotateImg,15000);
$('#feature-links a').click(function() {
if (!$(this).hasClass('a-active')) {
clearInterval(rotateTimer);
switchToImg($(this).attr('class'));
}
});
function switchToImg(image) {
var $featureImage = $('#feature-image');
$featureImage.fadeOut(200, function() {
$featureImage.css('background-image', 'url(images/main_' + image + '.jpg)').fadeIn(200);
$('#feature-detail div').removeClass('d-active').filter('.d' + image).addClass('d-active');
});
$('#feature-links a').removeClass('a-active').filter('.' + image).addClass('a-active');
};
function rotateImg() {
var next = 'a' + (parseInt($('#feature-links a.a-active').attr('class').match(/[0-9]/))+parseInt(1));
if (!$('#feature-links a').hasClass(next))
next = 'a1';
switchToImg(next);
}
});
This script works on class names of <a> tags that allow a user to manually switch to an image. As well as this, rotateImg() is providing an automated image/text cycle every 15 seconds with the help of setInterval().
The problem I have is with setInterval() re-initialising once a user has clicked on a link manually.
In the .click function I clear the interval timer and then make a call to the switchToImg() function with the class name of the <a> tag that was clicked on passed as a variable.
I'm trying to work out how I can re-set the timer to avoid a user clicking on a link towards the end of the cycle and having it switch immediately to the next image.
I have researched building my own callback function in to switchToImg() so that once the function has completed the timer is reset, ideally I'd like this to be a longer time initially (30 seconds for example) but then settle back down into the 15 second clock. My research however has lead me to a load of different repositories that I'm having difficulty making head or tail of.
Any guidance as to how I can build this functionality into the script would be really appreacited. Thanks for your time. :)
I'm not 100% sure I follow what you're asking, but if what you're trying to do is to restart the interval timer after a delay after the user clicks, then you could do that like this:
$('#feature-links a').click(function() {
if (!$(this).hasClass('a-active')) {
clearInterval(rotateTimer);
switchToImg($(this).attr('class'));
setTimeout(function() {
rotateTimer = setInterval(rotateImg, 15*1000);
}, 15*1000);
}
});
You would be using a one-shot setTimeout() call to restart the interval timer after a 15 second delay. This would give you 15+15=30 seconds before the next image switched again after a click and then 15 seconds each time after that.
Not sure I understand the question correctly. But basically I get that you want to prevent the timer from happening after the user clicks. Shouldn't calling setInterval right after switchToImg do exactly that? It'll call switchToImg then after every 15 seconds from the click of the user.