How to show and hide an image properly in javascript? - 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();
}

Related

If div text equals certain text do something?

Cannot for the life of me get this to work. Even when removing the AJAX POST function, it still doesn't work. There is no alert or anything. Here is the JSFiddle and code:
HTML
<div class="notification">
<div class="title gooddog">test</div>
<div class="reason helvetica"></div>
</div>
<script>
var interval = setInterval(function(){
var Winner = $(".notification .title gooddog").text();
if(Winner == "test") {
$.ajax({
url: "Won.php",
type: "POST",
data: { Winner : Winner }
})
.success(function(data) {
console.log('foo', data);
});
}
},1000);
</script>
It is meant to trigger/check the div text for changes every 1 seconds, but as you can see, it's doing nothing..
var Winner = $(".notification .title gooddog").text();
should be
var Winner = $(".notification .title.gooddog").text();
jsfiddle http://jsfiddle.net/abwp5u21/8/
You've got several issues...
You are using jQuery syntax but you are not including the jQuery plugin...at least not in the fiddle
Not an issue in this case, but if you want to get whatever is inside a div use the html function rather than the text function
As #Cattla pointed out in her answer to the proper "multi-class" selector is .title.gooddog
I wouldn't be surprised if you had more issues on the server-side as well. Here's an updated JS Fiddler

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.

Do not show social buttons (loaded via jquery) till they all are completely loaded

In my wordpress site, I am using social buttons gathered in a bar.
These buttons are dynamically updated when the content is updated via jquery-ajax.
function update_social(str)
{
$(".dd_outer").fadeOut("slow");
UpdateLikeButton(str);
UpdateTweetButton(str);
UpdatePlus1Button(str);
$(".dd_outer").fadeIn('slow')
}
where the str parameter is the ID of the post. and dd_outer is the wrapper div of the floating bar. I am calling update_social when I call the function responsible of dynamically loading post contents via AJAX.
Everything works like a charm, but the problem is that, sometimes the bar fades in before the social buttons are completely loaded. How can I make the total bar do not appear till all buttons are loaded?
I thought FadeIn and FadeOut are enough. Appreciated is your help.
Edit:
function UpdateLikeButton(str)
{
var elem = $(document.createElement("fb:like"));
elem.attr("href", "http://www.bag.com/Arabic/Arra2issia/"+str+"/");
elem.attr("send", "false");
elem.attr("layout", "box_count");
elem.attr("show_faces", "false");
$("#zzzz").empty().append(elem);
FB.XFBML.parse($("#zzzz").get(0));
}
function UpdateTweetButton(str)
{
var elem3 = $(document.createElement("a"));
elem3.attr("class", "twitter-share-button");
elem3.attr("href","http://twitter.com/share");
elem3.attr("data-url","http://www.bagh.com/"+str+"/");
elem3.attr("data-counturl","http://www.bagh.com/"+str+"/");
elem3.attr("data-count", "vertical");
elem3.attr("data-via", "#");
elem3.attr("data-text",str);
elem3.attr("data-lang","en");
$("#tweet").empty().append(elem3);
$.getScript("http://platform.twitter.com/widgets.js",function(){
twttr.widgets.load();
});
}
function UpdatePlus1Button(str)
{
var elem4 = $(document.createElement("g:plusone"));
elem4.attr("href","http://www.bagh.com/"+str+"/");
elem4.attr("size", "tall");
$("#plus1").empty().append(elem4);
$.getScript("https://apis.google.com/js/plusone.js");
}
Original buttons :
<div id="zzzz" ><fb:like href="<?php the_permalink();?>" send="false" show_faces="false" layout="box_count"></fb:like></div>
<div id="plus1"><g:plusone size='tall' href='<?php the_permalink();?>'></g:plusone></div>
<div id="tweet"></div>
Add return in your functions like this :
function UpdateTweetButton(str)
{
var elem3 = $(document.createElement("a"));
elem3.attr("class", "twitter-share-button");
elem3.attr("href","http://twitter.com/share");
elem3.attr("data-url","http://website/"+str+"/");
elem3.attr("data-counturl","http://website/"+str+"/");
elem3.attr("data-count", "vertical");
elem3.attr("data-via", "#");
elem3.attr("data-text",str);
elem3.attr("data-lang","en");
$("#tweet").empty().append(elem3);
return $.getScript("http://platform.twitter.com/widgets.js",function(){
twttr.widgets.load();
});
}
function UpdatePlus1Button(str)
{
var elem4 = $(document.createElement("g:plusone"));
elem4.attr("href","http://website/"+str+"/");
elem4.attr("size", "tall");
$("#plus1").empty().append(elem4);
return $.getScript("https://apis.google.com/js/plusone.js");
}
Call them like this :
function update_social(str)
{
$(".dd_outer").fadeOut("slow");
UpdateLikeButton(str);
$.when(UpdateTweetButton(str), UpdatePlus1Button(str)).done(function(){
$(".dd_outer").fadeIn('slow');
});
}
I think you might need to call the code in a callback from the fadeOut function, so that it doesn't run until the bar has faded out... Try
function update_social(str)
{
$(".dd_outer").fadeOut("slow");
UpdateLikeButton(str);
UpdateTweetButton(str);
UpdatePlus1Button(str);
//Make fadeIn wait 1 second before running to allow button functions to complete
setTimeout(function(){
$(".dd_outer").fadeIn('slow');
},1000);
};

Swipe JS not working with populated content

I'm using Swipe JS 2.
If I make the HTML structure myself, it works perfectly, but if I populate the HTML with content coming from the jQuery, it stops on the second slide.
My HTML structure:
<div id="map" class="swipe">
<div class="swipe-wrap">
<div class="city" id="current">
<div class="location">Current Location</div>
</div>
</div>
</div>
<nav>
<ul id="position">
<li class="on">Current location</li>
</ul>
</nav>
This is my structure on the jQuery.
$.getJSON("http://localhost/locations.php", function(localdata) {
$.each(localdata.locations, function(i, geolocal){
var vcountry = geolocal['country'];
var vregion = geolocal['region'];
var vcity = geolocal['city'];
country = vcountry.replace(' ','_');
region = vregion.replace(' ','_');
city = vcity.replace(' ','_');
// THE PROBLEM IS HERE. IF I USE AJAX OR GETJSON HERE INSIDE THE OTHER GETJSON, THE SWIPE IS BROKEN.
$.ajax({
type: "GET",
url: "http://localhost/remotexml.php?url=http://www.yr.no/place/"+ country +"/"+ region +"/"+ city +"/forecast.xml",
success: function(xml) {
var localName = $(xml).find('location name').text();
$('#map div.swipe-wrap .city:last-child').after('\n<div class="city">\n<div class="location">'+localName+'</div>\n</div>\n</div>');
$('#position').append('\n<li>'+localName+'</li>');
}
});
});
})
.success(function() { })
.error(function() { })
.complete(function() {
var slider =
Swipe(document.getElementById('map'), {
auto: 5000,
continuous: true,
callback: function(pos) {
var i = bullets.length;
while (i--) {
bullets[i].className = ' ';
}
bullets[pos].className = 'on';
}
});
var bullets = document.getElementById('position').getElementsByTagName('li');
});
What happens is: when I see the HTML created by the jQuery, is perfect. jQuery is creating the divs inside the slider and the lis inside the list. Perfect. When I run the website, load and starts perfectly, but then, when changes slide, stops on the second slide, and the second slide is blank. Nothing there. Even thought there is content on the HTML.
The most weird part? If I start the Developer Tools (Command + Alt + I on Chrome), right after the website loads, it WORKS PERFECTLY. What kind of bizar behavior is this? :D
Anybody can help me to make this Swipe JS to run?
If you're populating the slider with content via an AJAX request, then you will most likely have to wait until that AJAX request is finished before you build the slider - i.e. in the success callback of your AJAX function.

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