jQuery toggling an animation (with an image too) - javascript

I want to toggle two separate properties on a click event:
1) An image within a div - toggling the src attribute
2) The absolute positioning of the div - toggling the animate("top":"0px") bit
Here's the HTML
<div id="emailme">
<a id="email" href="mailto:xxx#gmail.com">xxx#gmail.com</a>
<div id="emailmecopy">email me</div>
<img id="emaildown"src="images/downbutton.png">
</div>
Now I've sorted the src toggling, but can't work out how to toggle the animation bit:
$("#emailme img").on({
'click': function() {
var src = ($(this).attr('src') === 'images/downbutton.png')
? 'images/upbutton.png'
: 'images/downbutton.png';
$(this).attr('src', src); //THIS TOGGLES THE IMAGE SRC
//BUT WHAT DO I PUT HERE TO TOGGLE ANIMATE BETWEEN ("top":"0px") and
//("top":"-50px") IN THE SAME CLICK??
}
});
Any help much appreciated!

if($("#emailme img").css('top') == '0px'){
$("#emailme img").stop().animate({top:'-50px'},1000);
};
if($("#emailme img").css('top') == '-50px'){
$("#emailme img").stop().animate({top:'0px'},1000);
};
also check this out:
$('body').on('click', '#emailme img', function (e){
$(this).attr('src', $(this).attr('src')=='images/downbutton.png'?'images/upbutton.png':'images/downbutton.png');
if($(this).css('top') == '0px'){
$(this).stop().animate({top:'-50px'},1000);
};
if($(this).css('top') == '-50px'){
$(this).stop().animate({top:'0pg'},1000);
};
});

If you refactor your code a bit you can do it like this. I suppose this is what you were looking for...
$("#emailme img").on({
'click': function() {
var $this = $(this);
var src = $this.attr('src');
var isUp = src === 'images/upbutton.png';
var newSrc = 'images/'+ (isUp ? 'downbutton' : 'upbutton') +'.png';
$this.attr('src', newSrc)
.animate({ top: (isUp ? '-50' : '0') +'px' });
}
});

Related

Wordpress Filter Buttons: Content fading out and fading in

I am using this javascript to turn on and off the display of certain content on a website, depending on the contents category set in the backend:
<script>
var $btns = $('.btn').click(function() {
if (this.id == 'all') {
$('.projekte > .post').fadeIn(600);
} else {
var $el = $('.' + this.id).fadeIn(600);
$('.projekte > .post').not($el).hide();
}
$btns.removeClass('active');
$(this).addClass('active');
})
</script>
When the content which is being set to active (i.e. is being displayed) it fades in nicely. How can I let the disappearing content fade out just as smoothly? As of right now it merely disappears instantly, which heavily breaks with the visual feel of the website.
A live demo of the script can be seen here: http://udkdev.skopec.de/category/projekte/
Have you tried fadeOut();?
<script>
var $btns = $('.btn').click(function() {
if (this.id == 'all') {
$('.projekte > .post').fadeIn(600);
} else {
var $el = $('.' + this.id).fadeIn(600);
$('.projekte > .post').not($el).fadeOut(600);
}
$btns.removeClass('active');
$(this).addClass('active');
})
</script>
Use the jQuery method - fadeOut() or define css transitions for the element class.
$('.projekte > .post').not($el).hide();
Can be replaced with
$('.projekte > .post').not($el).fadeOut();

Preload image on event

How can I preload image only when event starts, i.e. .scroll or .click ?
What happens now is, image loads along with website, and I want to prevent this from happening.
Thanks.
Use .one() , .appendTo()
$(element).one("click", function() {
$("<img src=/path/to/img/>").appendTo(/* target element */)
})
$(window).one("scroll", function() {
$("<img src=/path/to/img/>").appendTo(/* target element */)
})
Maybe something like this:
$(function() {
$('img').each(function() {
var self = $(this);
self.attr('data-src', self.attr('src'));
self.removeAttr('src');
});
var loaded = false;
function loadImages() {
if (!loaded) {
$('img').each(function() {
var self = $(this);
self.attr('src', self.data('src'));
});
loaded = true;
}
}
$('button').click(loadImages);
$(window).scroll(function() {
loadImages();
$(this).unbind('scroll');
});
});
if the javascript is executed after images are loaded you can try to change img src to data-src in html file.
You could create an image tag with the source in an data attribute:
<img data-src="your_image.jpg">
And then load it on an event:
$('body').on('click', function(){
$('img[data-src]').each(function(i, img){
$img = $(img);
$img.attr('src', $img.data('src'));
$img.removeAttr('data-src');
});
});
This should work
$(function(){
$(document).one("scroll, click", function(){
loadImages();
})
})
Here loadImage is a function which will load your images on click/scroll event. "one" method will make sure that it only happens only once else you will end up loading images every time someone click or scroll.
var src = 'location/file.jpg';
$(document).on('click', function(){
$('target').append('<img src="' +src+ '" />');
});

jquery swap image on element click not functioning

I am trying to swap an image on click with jquery. I have got it to work with the click being bound to the image class. However, if I try and wrap the function and bind the event to a button or anchor, it will not swap the images. Here is the jquery:
<script type="text/javascript">
jQuery(document).ready(function( $ ) {
$(".test_toggle").click(function(){
$(this).find(".img-swap").live('click', function() {
if ($(this).attr("class") == "img-swap") {
this.src = this.src.replace("_off","_on");
} else {
this.src = this.src.replace("_on","_off");
}
$(this).toggleClass("on");
});
});
});
</script>
This worked:
jQuery(document).ready(function( $ ) {
$(".img-swap").live('click', function() {
if ($(this).attr("class") == "img-swap") {
this.src = this.src.replace("_off","_on");
} else {
this.src = this.src.replace("_on","_off");
}
$(this).toggleClass("on");
});
});
Any help is greatly appreciated.
I don't think there's any need to delegate the event listeners so I've removed them. Simply add the click event to the image and then you can manually 'trigger' a click on it when the .test-toggle is clicked. E.G:
$(function() {
//add on click event
$(".img-swap").on('click', function() {
if (this.src.indexOf("_off")>0) {
this.src = this.src.replace("_off","_on");
} else {
this.src = this.src.replace("_on","_off");
}
});
//add remote trigger
$(".test_toggle").on('click', function(){
$(".img-swap").trigger("click");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="img-swap" src="https://placehold.it/300?text=_off" />
<button class="test_toggle">test toggle</button>
Thats because unlike like img.
a or button doesn't have a src attribute.
So when you bind the event to a button or anchor, this.src in your second instance of the code will be invalid.
I would delete this line:
$(this).find(".img-swap").live('click', function() {
What is it's purpose? You can swap this image right after the first click, right?
Also, make sure that .img-swap is inside the tag with class test_toggle.
You are using:
$(this).find(".img-swap")
find() searches only in children of selected element.
If it's not nested use
$(".img-swap")
instead of:
$(this).find(".img-swap")
I have re-written the js, but not tested. Can I nest clicks?
$(".test_toggle").click(function(){
$.find(".img-swap").click(function(){
if ($(this).attr("class") == "img-swap") {
this.src = this.src.replace("_off","_on");
} else {
this.src = this.src.replace("_on","_off");
}
$(this).toggleClass("on");
});
});

Why changing img src with jQuery works incorrectly?

Well, the task is to change img src on click.
It was not a problem to do it.
But I'd like to have some effect while changing it.
So, I used fadeOut and fadeIn. Problem is when the img src is changing the img starts "sparkling / blinking".
You can see an example here
http://www.coffee-cult.ru/slidersupreme
(rectangle in top right corner activates slider buttons)
and the code,
$main_image = $("img").first();
$("#prev_slide").click(function(e) {
e.preventDefault();
$main_image.fadeOut(400, function() {
$main_image.attr('src', images[0]);
}).fadeIn(400);
});
$("#next_slide").click(function(e) {
e.preventDefault();
$main_image.fadeOut(400, function() {
$main_image.attr('src', images[1]);
}).fadeIn(400);
});
you can try to use
$(this).attr();
instead of
$main_image.attr();
It has something to do with your other scripts on the page. Here in the fiddle it looks kind of alright with the same code: http://jsfiddle.net/ewyLcm0s/
var images = ['http://lorempixel.com/100/100/people/1','http://lorempixel.com/100/100/people/2'],
$main_image = $("img").first();
$("#prev_slide").click(function(e) {
e.preventDefault();
$main_image.fadeOut(400, function() {
$(this).attr('src', images[0]).fadeIn(400);
});
});
$("#next_slide").click(function(e) {
e.preventDefault();
$main_image.fadeOut(400, function() {
$(this).attr('src', images[1]).fadeIn(400);
});
});

Combining jQuery/JavaScript functions

Is there any way to combine all of this to reduce the amount of javascript?
$(document).ready(function() {
$(".individualImagebox img").bind("click", function()
{
var src = $(this).attr("src");
if (src.search(/Red\.jpg$/) >= 0) return;
// Removes the red overlay from the images folder
$('.individualImagebox img').attr( "src", function () {
var thisSRC = $(this).attr( "src");
return thisSRC.replace(/Red\.jpg$/, ".jpg");
});
// Adds the red overlay from the images folder
$(this).attr( "src", src.replace(/\.jpg$/, "Red.jpg") );
});
});
function ShowHide(index) {
var itemSelector = ".name:eq(" + index + ")";
$(".name .bio").fadeOut();
$(".name").not(itemSelector).fadeOut();
$(itemSelector).animate({"height": "show"}, { duration: 500 });
$(itemSelector + " .bio").animate({"height": "show"}, { duration: 500 });
}
$(function() { // $(function(){}) is a shortcut of $(document).ready(function(){})
var $activeImg; // Maintain a reference to the last activated img
$(".individualImagebox img").click(function(){
if (!!$activeImg) {
$activeImg.attr("src", function(i, src){
return src.replace(/(.+)Red\.jpg$/, "$1.jpg");
});
}
$activeImg = $(this).attr("src", function(i, src){ // replace attribute and updates active img reference
return src.replace(/(.+)\.jpg$/, "$1Red.jpg");
});
});
});
I don’t know exactly what you are trying to do but if possible, you should toggling a class instead of modifying the src attribute.
Combining methods won't save you space. Take a look at
http://developer.yahoo.com/yui/compressor/

Categories