Jquery and PhP: Adding Animations - javascript

I am creating a a random number generator that has a big blue button, that you click. As soon as you click it, I use jquery and ajax to submit the form without refreshing the page. I get a random number between 0 and 100. What I do is that I replace the value of the button with the number that was generated. Here is the code that I have...
$('form.roll').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function (index, value) {
var that = $(this),
name = that.attr('name'),
value = that.va();
data[name] = value;
});
$.ajax ({
url: url,
type: type,
data: data,
success: function(response) {
$(function() {
$("#roll").val(response);
});
}
});
console.log(data);
return false;
});
and here is the button
<input type="submit" class="btn btn-primary btn-lg btn-block" id="roll" value="Roll Dice">
Now this seems to work, but it does not look good. I would like to animate it. What I want to do is that is kind of flashes in, stays for a few seconds, and then slowly fades away back to "roll dice", like the animation here: (just click on superuser and change it, you will see the animation.
http://vitalets.github.io/x-editable/demo.html
What i want is that if it is less that 50, the flash is green, and when it rolls more that 50 its red. The number that is displayed is something like "29.67". Two digit number, with two decimals.
I would also like to add loading gif while the php function is being processed.
I hope this makes sense, and that you can help me out. Thanks a lot for your time!

jQuery UI provides a Highlight effect which probably matches your need: http://api.jqueryui.com/highlight-effect/. Color is customizable.
Usage is:
$("#number").effect('highlight', { color: 'red' });
I made up a fiddle for your scenario: http://jsfiddle.net/QG7hE/1/

Related

The value of my newly appended button returns undefined or nothing at all

I am trying to obtain the value of a newly appended button, however it always logs undefined or nothing. I have tried many methods, such as .val(), .textContent, and .value, as I have found those on here.
Here is my code.
}).done(function (response) {
var lat = response.data[0].latitude;
var long = response.data[0].longitude;
//Appends new button based on recent search
searchHistory.append(`<button class="col-12 btn border-info m-1" id="prevSearch">${textInput.val().toLowerCase().split(' ').map((s) => s.charAt(0).toUpperCase() + s.substring(1)).join(' ')}</button>`);
var previousSearch = $("#prevSearch");
previousSearch.on('click', () => {
console.log($(this).val();
console.log(document.getElementById("prevSearch").textContent);
})
})
The first log under the click function returns undefined, while the second one returns the actual content. However it only works with the first button that is appended when I try a console.log("test").
So in summary, I have 2 Issues, I can't get the value of the button and only the first button works when tested with a simple console log.
Any help would be greatly appreciated.
You're getting the button by ID. If you're adding multiple elements with the same ID, that won't work since IDs must be unique within the document.
As for your button value, I'd say just use $(this).text(). Browser support for the element content as HTMLButtonElement.value has a patchy history.
I'd just use the following
const button = $("<button>", {
type: "button",
"class": "prevSearch col-12 btn border-info m-1",
text: textInput.val().replace(/(^| )[a-z]/g, c => c.toUpperCase())
}).appendTo(searchHistory)
button.on("click", function() {
console.log($(this).text())
})
You could also move the event handling to a delegated handler outside of this code that can handle all current and future button clicks
searchHistory.on("click", ".prevSearch", function() {
console.log($(this).text())
})

How to click just some buttons of a website?

I need to do the following:
I have the positions 1 to 16, and the names of the people. Each number belongs to each person:
POSITION 1 is for ROBERT, number 3 is for JULIA, etc
The ASK button for ROBERT is exactly the same as the one for JULIA - it has the same identifier number (or variable, idk how it's called in javascript), and it has the same function, except it messages a different person.
So, how do I click ASK automatically just for those whose name ends in KE?
I found a script that does a part of what I need, and I believe that with this script, plus a counter I will achieve what I need.
However, how do I unify these two : the counter with the below code?
I can't find the way/logic to do it.
Code:
function clickAsk(){
$('button.ASK').on(
'click', function(){
console.log('You clicked',$(this).html())
}
);
$('button.ASK').each(
function(index){
setTimeout(()=>{$(this).click()},index*1000);
}
);
}
setTimeout(clickAsk,850)
This clicks every ASK button, first the 1st, then the 2nd, then the 3rd, etc. But I only need to click ASK for the persons whose name ends in KE ( i.e. 2.JAKE and 4.Spike )
PS: Just in case, the Timeout is fine, i will use it
You can use an id but I find it better to use the data selector.
$('.user').each(function () {
var $this = $(this);
$this.on("click", function () {
alert($(this).data('users'));
var str = $this.text();
if (str.match(/ke$/)){
alert($this.text());
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="user" data-users="user1" >Mike</button>
<br>
<button class="user" data-users="user2" >Jake</button>
<br>
<button class="user" data-users="user3" >Henry</button>
First add a data attrib to every button, which holds the name of the person who the button belongs to:
<button class="user" data-name="Robert" value="ASK">
<button class="user" data-name="Julia" value="ASK">
etc...
Then you can use the following code to check for endings:
$('.user').each(function (i, o) {
if ($(o).data('name').endsWith('KE')) {
$(o).click();
}
});

How to show and hide an image properly in javascript?

I've been having issues trying to show and hide images inside of my ajax request function. In order to be clear of what I'm trying to do, I make a video less than 1 minute click here. If you see in the web console, there's a variable that is changing from "ocupado" to "libre" and that means if there's a free or busy parking space. So It kind of work because in the beginning my variable "data" = ocupado shows a car image, then when it changes to "data" = libre hide the car image. The problem starts when it changes again to "data" = ocupadobecause It doesn't show any car image.
Here's my code for ajax function
<script src="js/jQuery.js"></script>
<script type="text/javascript">
setInterval(function(){
$("img").error(function () {
$(this).unbind("error").attr("src", "");
});
$(function ()
{
$.ajax({
url: 'api.php',
data: "",
success: function(data)
{
console.log(data);
if (data === "libre"){
$("#slave1free").hide();
$("#slave1busy").hide();
}else{
$("slave1free").show();
$("slave1busy").show();
}
}
});
})
}, 1000);
<div class="chart">
<div class="chartimage"><img src="images/parkinglot.jpg"></div>
<div class="image" id = "esclavo1">
<div class "free" id = "slave1free"><img src="images/carfree.png"></div>qQ
<div class "busy" id = "slave1busy"><img src="images/carbusy.png"></div>
</div>
By the way, carfree.png and carbusy.png are those images that are shown in the video next to "estacionamiento libre" and "estacionamiento ocupado". I put one image in top of the other because I was planning to show and hide both images according to value of data ("libre" or "ocupado").
Edit: Yes, I'm hidding both and showing both on purpose because I wanted to see where's the problem. Despite that both are showing or hidding at the same time, It would appear both images(one in top of the other) when "data"=ocupado ?
note that you are hiding the two items, or showing them at the same time... shouldn't be one of each?
if (data === "libre") {
$("#slave1free").show();
$("#slave1busy").hide();
} else{
$("slave1free").hide();
$("slave1busy").show();
}
-edit-
Just realized that you are missing the id selector ( # ) on the else
if (data === "libre") {
$("#slave1free").show();
$("#slave1busy").hide();
} else{
$("#slave1free").hide();
$("#slave1busy").show();
}

jquery textarea does not updates its value

I have site with some columns on it and theese columns can be editet by a textarea, if the column you want to edit have some content, that old content will be put into the textarea. Then on the save button is stores the value of that text area into a variable, if i alert this variable it alerts the same value as the old content.
The idea is biscally this: FIDDLE
Where the textarea updates a div and when you hit save and get the content in the div when you hit edit. This simple works as it should, but I'm having trupple with my code, and i cant find the error. And there is no error in the console aswell.
The differense on the exmaple i made and the place of my problem is that i use an ajax call to get the old content.
First here is what happens on the edit click:
$('body').on('click', '.edit_column', function() {
column_to_edit = $(this).parent().parent().attr('id');
current_step = "edit";
$.ajax({
url: 'pageEditor_ajax.php',
dataType: 'json',
async: false,
type: 'post',
data: {
item_id: column_to_edit,
mode: "edit_item"
}, success:function(s) {
element_type = s.type;
old_content = s.content;
}, error:function(e) {
alert('Error!');
}
});
if(element_type == 'text') {
$('.input_type').html('<textarea class="dialog_editor element_content"></textarea>');
}
$('.element_content').val(old_content);
$('.column_tool_dialog').css('display', 'block');
$('#edit_column_dialog').css('display', 'block');
$('#edit_column_dialog').animate({
left: "-=300px",
opacity: "1"
},500);
});
First i find the id of the column i want to edit so I'm shure that im editing the right column i the database.
The current_step variable is only for the looks, have some different dialog boxes.
The i make my ajax call that returns with success.
Then i have an if statement to check what type of column it is, i have 3 types, the two others is image and headline, havn't startet on them yet because this is not working yet.
The if statement should just build the inputs need to edit that type of column.
After the input fields a build it put the old_content into the textarea, this works fine too. The last few line is just for the looks agen to animate to the next dialog box. So my edit step works (I think).
Then you see the textarea, and i have the old content in it. When you click the save button, this happens:
$('#element_edit_button').click(function(e) {
e.preventDefault();
new_content = $('.element_content').val();
alert(new_content);
$.ajax({
url: 'pageEditor_ajax.php',
dataType: 'json',
async: false,
type: 'post',
data: {
item_id: column_to_edit,
item_content: new_content,
col_type: element_type,
mode: "save_item",
item_attr_alt_tag: alt_tag,
item_attr_title_tag: title_tag
}, success:function(s) {
}, error:function(e) {
alert('Der skete en fejl!');
}
});
$('li#'+column_id+' .preview_content').html(new_content);
$('li#'+column_id+' > div > small').html(new_content);
});
In this step i have a lot of things just for the looks, so i have excluded them this time. But the problem is fairly simple to explain here, the new_content variable is identic with the old_content? So all the places where is use the new_content the stuff dont get updated.
EDIT
Here is the html where it all happens:
<div id=\"edit_column_dialog\" class=\"column_tool_dialog_box\">
<div class=\"close\">x</div>
<h3>Rediger dit element</h3>
<form method=\"post\" id=\"save_element\">
<p class=\"error_message\"></p>
<div class=\"input_type\"></div>
<input id=\"element_edit_button\" class=\"green dialog_button\" type=\"submit\" value=\"Gem element\" />
</form>
</div>
</div>
Sorry for the long post, hope someone have an awnser.
As others have said, your jquery and even html could use some cleaning up. With that said, assuming I understand your question correctly, I think you're just missing a line in your #element_edit_button click event:
$('.element_content').val(new_content);
That should do the trick.

Highlight image borders with Ajax request

First, some visualization of the code.
I have the following images that are dynamically generated from jquery. They're made upon user request:
<img id="i13133" src="someimage.jpg" />
<img id="i13232" src="someimage1.jpg" />
<img id="i14432" src="someimage2.jpg" />
<img id="i16432" src="someimage3.jpg" />
<img id="i18422" src="someimage4.jpg" />
I have an AJAX loop that repeats every 15 seconds using jQuery and it contains the following code:
Note: The if statement is inside the Ajax loop.
Where imgId is the requested ID from the Ajax call.
//Passes the IDs retrieved from Ajax, if the IDs exist on the page the animation is triggered.
if ( $('#i' + imgId ).length )
{
var pickimage = '#i' + imgId;
var stop = false;
function highlight(pickimage) {
$(pickimage).animate({color: "yellow"}, 1000, function () {
$(pickimage ).animate({color: "black"}, 1000, function () {
if (!stop) highlight(pickimage);
});
});
}
// Start the loop
highlight(pickimage);
}
It works great, even with multiple images. But I had originally used this with one image.
The problem is I need an interrupt. Something like:
$(img).click(function () {
stop = true;
});
There's two problems:
1.)This obviously stops all animations. I can't wrap my head around how I could write something that only stops the animation of the image that's clicked.
2.)The Ajax retrieves IDs, sometimes those IDs appear more than once every few minutes, which means it would repeat the animations on top of each other if the image exists. I could use some help figuring out how to detect if an animation is already running on an image, and do nothing if the animation is already triggered on an image.
You can hit two birds with one stone ;)
1) Don't use the stop variable. Add a class to each img:
// Instead of: var stop = false;
$(pickimage).addClass("animating");
// Instead of: if (!stop) highlight(pickimage);
if ($(pickimage).hasClass("animating")) highlight(pickimage);
// Instead of: $(img).click(function () { stop = true; });
$(img).click(function () { $(this).removeClass("animating"); });
2) Same thing, check the class!
if ($(pickimage).hasClass("animating")) return;

Categories