JQuery event to seek changes - javascript

I have a date changing script. How can i prevent refreshing the date on page refresh? Since my date is stored in h3 as a simple string. Just in future i need to show specific data corresponding to date. Does Jquery .change() method is used only on input fields? And also is it possible to use AJAX to update some data corresponding to the date stored?
Demo : Jsfiddle
<button id="yesterday">yesterday</button>
<button id="tomorrow">tomorrow</button>
<h3 id="today_date"></h3>

To stop the date changing on refresh, you'll need to store it somewhere. Probably best done with local storage as opposed to a database, until the user has set a final date. You don't want to add to a DB on every click of the button.
Using local storage, you would set the date on each click of the button, and on page load check to see if a date has been saved. If so, show that date.
You can see how it can be done by looking at this pen: http://codepen.io/jhealey5/pen/KldjC - It's similar in that it adds to storage on each click of adding a note, and checks storage on page load. Should be able to adapt it to your needs.
And yes, you can then post it somewhere with Ajax whenever. But it's probably not a good idea to do it every time the button is clicked, depending on what you're trying to do exactly.
Hope that helps.
Ed: have to add some code for the codepen link...
localStorage["notes"] = JSON.stringify(storedNotes)

You can use 'DOMSubtreeModified' event to check whether the value is changed.
$("#today_date").on('DOMSubtreeModified', function () {
alert("date changed");
});
if your target browser is IE, you can use 'propertychange' event.
$("#today_date").on('DOMSubtreeModified propertychange', function () {
alert("date changed");
});
http://jsfiddle.net/7LXPq/819/

Related

Cannot update text element using javascript. When button is clicked text returns to previous value

UPDATE/SOLUTION
Hey Folk!
Thnx to all that previously provided some info to resolve this challenge. Lastnite, I decided to tackle this again, yea after more than a year LOL. Well the answer came fairly quickly. Turns out that the site required an event trigger that validates the input before it continues the process after the submit 'action' is envoked. Now, in my current setup I had to PASTE the new text value and then have the javacript do its job, this is not ideal since the operation can happen more than 100 times or more per day. Then the light buble came on! Lets have javascript, instead of me, execute a paste command!
document.getElementsByClassName('input-number')[0].value = ""; //clear input
document.getElementsByClassName('input-number')[0].focus(); //set focus
document.execCommand('insertText', false, '0.0000003'); // 'paste' new text value
Of course '0.0000003' will be a variable :).
That did the job!!! The code can now change the text, click on the submit button and the new text is used! Hope this helps others with similar issue.
Take care,
Jess
PS: Yes, I know execCommand() is obsolete, will update that later.. for now it works fine.
===============================================================
I am trying to update text element and then click a button using java script but have no luck with the value of the text element being the value that I programmed. It reverts back to the value that was on the element before.
The website in question is: https://betfury.io/dapps/dice
Code Snippets:
//first set text to x value
document.getElementsByClassName('inp-number')[0].value=0.000001
//Then I click on the button to start the game
document.getElementsByClassName('btn btn_blue btn_large')[2].click();
When the scripts are executed you can see the change and the button clicked but after the click, the text value returns to what it was before and not the 0.000001 value I want it to be.
Please advice.
I don't know about page that linked by you, But maybe you want set value of Web-game.
Generally, Element value of Web-game is just display value, and real value stored in other data store. For example, Local Storage, Local Variable, Server Database...
I recommend try debugger to know "How this game works". Then maybe you can cheating that game.

Submit button working at times but stops working on several app usage

Thanks in advance
I am trying to get the value of an text area input field using vanila js but I don't get the updated value, that is , I have already fed in some pre-value for the tex tarea which is updated accordingly but upon posting, the only data I get is the pre-fed value.
document.getElementById('jjeditlab').elements.namedItem('textarea_input_{{ $item->results->id }}').value
You get the value at the time your code runs.
If you want to get the value later, then run the code later.
e.g. in an event handler or setInterval.

Change or update the visible part of query string in the browser address bar using JS or jQuery?

I am wondering is there any solution to change or update the URL's query string part (visible in the browser's address bar) with some new values by clicking on some checkboxes through JavaScript or Jquery. I want to do this without any jQuery plugin.
When the user will click on any checkbox in a group then the data will be fetched from the database based on the user's selected value of checkbox. Along with it, the query string of URL will also be changed with new updated value. Note that the page will never be reloaded in this whole procedure. We can run through AJAX when checkbox is checked. How we can achieve this? A demo will be very much appreciated.
Yeah, this is a very common thing to do. window.replaceState is the function you're looking for. Alternatively you could also use pushState if you want to allow the user to be able to go back to the previous state of checkboxes, but that's more work and not always expected.
Then again, you actually need something to change one URL into another. Manipulating the URL as string is counter productive, so instead you can use a library like URI.js.
Use window.history like so :
window.history.pushState('page2', 'Title', '/new-uri');
For your case , you will have 2 nested functions: Event Listener which contains AJAX call + Callback of this ajax call :
$('[input]').change(function(){
if(this.checked){
//AJAX
$.get("URL",{},function(data){
//AJAX - Callback
window.history.pushState('page2', data.title, data.url);
});
}
});

Automatically updating a PHP variable when a radio button or dropdown menu item is selected

My classmates and I are building a small submission form in which a user submits shipping and billing information for their order.
The two main factors that effect the order price are the type of shipping the user selects ( $shippingType ) and the price of the item ( $initialPrice ). The variable $totalPrice is then defined which adds $shippingPrice and $initialPrice.
What we are working towards is having $totalPrice update when $shippingPrice is changed without the user having to resubmit the form. Can this be solved using php? Or would we have to use a jquery event to update the page in realtime.
You'll want to use some sort of jQuery as mentioned above. It's important to understand that PHP is only used either in AJAX, or before the page has loaded. Meaning you cannot use PHP on a page that has already been loaded. To change elements after it's loaded you would need to use javascript/jquery of some sort. I've attached a quick fiddle to illustrate an example of what I think you're looking for.
The gist of it is that you would bind a change event so that when the elements you want to use for mathing are changed you can update the other items.
$('#shipping').bind('focus, change', function() {
//Get the inital value of the #cost input
var initial_val = parseInt($("#cost").val());
//Value from the #shipping input
var additional = parseInt($("#shipping").val());
//Parsed ints because '+' is used for concatination as well, so making the vars ints will make '+' go back to math.
$("#cost").val(initial_val + additional);
});
No it's not the prettiest, but it works.
Here's the Fiddle:
http://jsfiddle.net/Lb486ck8/2/
You will have to use Javascript to accomplish this behavior. Furthermore, you will need to use AJAX (Asynchronous Javascript And XML) to make it work. AJAX is a way for Javascript to send requests to a web page "behind the scenes" while your page stays in the foreground.
http://api.jquery.com/jQuery.post/

Javascript to analyze a div?

So I figured I'd get a little bit of Javascript practice and work on my first Google Chrome extension. I'm making an extension that, when the user clicks the "Like" button on Facebook, if the post they click on is older than a certain threshold, then it prompts them to make sure they indeed meant to click "Like" on the post (to prevent accidental likes when stalking).
I have basic functionality down where if the user clicks like it prompts them to make sure they meant to hit like, and if they didn't meant to, they can cancel the like at that point. However, now I'm trying to add detection of whether a post is of a certain age or not, to only prompt when the post is old.
My source for what I have right now is located here:
https://github.com/mathur/StalkingCondom
Essentially, Facebook stores this data in a timestamp, and I want to know how to access the timestamp just from the post where the user is currently "liking" and not any of the other timestamps on the page.
Below is my code that runs when the document is loaded:
$(document).ready(function(){
$( ".UFILikeLink" ).click(function(e) {
if (confirm("Are you sure you want to like this?")) {
// like was intended, continue with usual behavior
}
else {
// like was not intended, lets stop that like!
e.stopPropagation();
e.preventDefault();
}
});
});
The timestamps are stored between abbr tags like below:
<abbr data-utime="1421210082" data-shorten="1" class="_5ptz timestamp livetimestamp">10 mins</abbr>`
Every post has its own div with certain unique ID.
Basically I need to wrap the entire UFILikeLink click function in an if statement where if the date is older than a certain date then execute the click function right? How would I make it so the Javascript finds the timestamp only within that one unique div?
Is anyone willing to point me in the right direction? Is this even feasibly possible? Thank you so much for your time!
First of all: Facebook's timeline gets updated via AJAX requests every time you reach the bottom, so adding a listener to $(".UFILikeLink") will only work on the first few links (loaded at the beginning). If you want it to work for ALL the links, you'll have to add a listener to the <body> element.
So you will use addEventListener('click', func(){...}, true) to add a listener for the click event, and set useCapture=true (last argument). With useCapture set as true you can prevent the events before they reach the target element and stop them when necessary. Then, inside the event listener you will check if the clicked element has class UFILikeButton, and, if so, continue.
Now, before writing down anything, you need to make some corrections considering the following facts:
The "Like" text that the user clicks is actually a <span>, and does not have the class "UFILikeLink", but its parent does. Here is the structure of a like link:
<a class="UFILikeLink" href="#" role="button" aria-live="polite" title="Like this" ...>
<span data-reactid=".27.1">Like</span>
</a>
You don't exactly know where the <abbr> element is located, so you'll need to search for it: using .parents(".userContentWrapper") you'll find the post body container, which contains the <abbr> element, then using .find("abbr") you'll finally get to it. Here is the full code:
var timestamp = +$(e.target).parents(".userContentWrapper").find("abbr").attr("data-utime");
*The + (plus) converts the string to a number
If the user clicks on "Unlike" instead of "Like", you should not display the prompt, so it is useful to check for the text contained inside the clicked element, like this:
$(e.target).text() == 'Unlike';
Facebook timestamps are in seconds, but JavaScript timestamps are in milliseconds. To compare them you have either to multiply the first one or divide the second one by 1000.
Here is the final code, to make things easier I created likeLink, which is the link with class "UFILikeLink", and likeSpan, which represents the text contained in the link (the one the user really clicks).
document.body.addEventListener('click', function(e) {
var likeLink = $(e.target.parentElement),
likeSpan = $(e.target),
timestamp, oldTimestamp;
// If the clicked element is not the Like button, just stop the function
if (!likeLink.hasClass("UFILikeLink")) return;
// If the users clicks to UNLIKE, you don't need to check
if (likeSpan.text() == 'Unlike') return;
timestamp = +likeLink.parents(".userContentWrapper").find("abbr").attr("data-utime");
// Set a limit of one month ago (2592000 seconds = 30 days)
oldTimestamp = +new Date()/1000 - 2592000;
// If the post is older than one month...
if (timestamp < oldTimestamp && !confirm("Are you sure you want to like this?")) {
// like was not intended, lets stop that like!
e.stopPropagation();
e.preventDefault();
}
}, true);
The above code will prompt the "Are you sure?" message for posts older than one month. You can edit the check variable to set it to older or newer posts.
Get a reference to the parent div however you want. If you know the Id for the div, that's an option. If they're all inside a container, maybe you can get it by ID and iterate over its children. You'd have to provide the markup to get a more specific answer on that part. Once you have that reference to the div, you can get the child element by tag name (assuming there's only one abbr tag inside, or at least there's are recognizable pattern). Here's an example of the call you could make to do it.
document.getElementById('parentDivId').getElementsByTagName('abbr')[0].getAttribute('data-utime');
Breaking that out into parts,
document.getElementById('parentDivId') gets a reference to the element with the specified ID, in this case a <div id="parentDivId">
.getElementsByTagName('abbr')[0] finds all child elements within the div that are <abbr> tags, and returns them in an array. The [0] part gets this first element from the array.
.getAttribute('data-utime') gets that attribute from the selected abbr element.
Is that clear?
See here for reference to the selectors you have available in vanilla javascript - http://www.w3schools.com/jsref/dom_obj_document.asp. If you're using jquery (looks like this question is tagged that way) it has its own set of selectors with additional flexibility.

Categories