Giving same classes unique identifyers to stop code repitition - javascript

I have this JS code
<script>
$('.tile').on('click', function () {
$(".tile").addClass("flipOutX");
setTimeout(function(){
$('.metro .tile-area-darkCrimson').css('backgroundColor','#4c7fb5');
$(".tile-group.main").css({ marginLeft:"-40px", width: "1080px"}).load("musability-musictherapy-company-overview.html");
}, 2000);
});
</script>
The .tile class applies to all the buttons which are all called tile .
Is there any way to introduce a unique identifier without having to repeat this script for every button individually.
This is an example of the tile ref in the html
<a class="tile double bg-tile1color live animated flipInX" data-click="transform">

use $(this), it applies only on the element you clicked
$('.tile').on('click', function() {
$(this).addClass("flipOutX");
setTimeout(function() {
$('.metro .tile-area-darkCrimson').css('backgroundColor', '#4c7fb5');
$(".tile-group.main").css({
marginLeft: "-40px",
width: "1080px"
}).load("musability-musictherapy-company-overview.html");
}, 2000);
});

Related

Navigate between divs with the same classname in jquery

I'm using a plugin that allow to add popup to images,i want that when i click on a popup i can navigate between all popups with previous and next buttons.
Here is my element when its showen :
<div class="imp-tooltip.imp-tooltip-visible" style="border-radius: 5px; padding: 20px; background: rgba(0, 0, 0, 0.9)"></div>
and i tried this :
<nav>
<button id="down" ></button>
<button id="up" ></button>
</nav>
var $currentElement = $(".imp-tooltip imp-tooltip-visible").first();
$("#down").click(function () {
var $nextElement = $currentElement.next('.imp-tooltip');
if($nextElement.length) {
$currentElement = $nextElement;
$('html, body').stop(true).animate({
scrollTop: $nextElement.offset().top
}, 1000);
}
return false;
});
$("#up").click(function () {
var $prevElement = $currentElement.prev('.imp-tooltip');
if($prevElement.length) {
$currentElement = $prevElement;
$('html, body').stop(true).animate({
scrollTop: $prevElement.offset().top
}, 1000);
}
return false;
});
There's a couple of little errors in your code.
HTML: class="imp-tooltip.imp-tooltip-visible"Should be: class="imp-tooltip imp-tooltip-visible"
JS: $(".imp-tooltip imp-tooltip-visible").first()Should be: $(".imp-tooltip-visible").first()
What is the purpose of the imp-tooltip-visible class? Is it there to indicate what is currently the active element? If so, then you forgot to remove this class from $currentElement before assigning a new element to it. And after performing this operation this class should be added to the new $currentElement. This would also make the .first() part in the selector redundant since there should only be one element with this class.
If on the other hand this class indicates which imp-tooltip divs are actually visibly available, then the next() and prev() functions should be targeting imp-tooltip-visible instead of imp-tooltip.

How to reduce my code in both jQuery and CSS

Here is my code:
jQuery:
$(document).ready(function () {
$("#news").hover(function () {
$('#news_img').animate({
height: 'toggle'
}, 290, function () {
});
});
$("#news1").hover(function () {
$('#news_img1').animate({
height: 'toggle'
}, 290, function () {
});
});
$("#news3").hover(function () {
$('#news_img3').animate({
height: 'toggle'
}, 290, function () {
});
});
$("#news4").hover(function () {
$('#news_img4').animate({
height: 'toggle'
}, 290, function () {
});
});
});
JSFIDDLE here:
http://jsfiddle.net/huydq91/N89Kw/
I would like to reduce my code and make it easier to manage in the future whenever I would love to add more <tr> or <td> tags without editing too much in the jQuery and CSS.
You can target the hover elements by its class news and find the target element by appending the last digits in the hovered element's id to news_img like
$(document).ready(function () {
$(".news").hover(function () {
$('#news_img' + this.id.replace('news', '')).stop(true).animate({
height: 'toggle'
}, 290, function () {});
});
});
Demo: Fiddle
You can remove the css part of the hover by adding some data-* attributes to the image like
<img src="http://i853.photobucket.com/albums/ab100/vimeo1903/Showroom1_zps923b43dc.jpg" border="0" alt="Showroom1" data-hover="http://i853.photobucket.com/albums/ab100/vimeo1903/Showroom1_1_zpse41d0851.jpg" />
then
$(document).ready(function () {
//since the news elements has a common class, use it to target all the news elements instead of using individual ids
$(".news").hover(function (e) {
//you can find the `news_img` within the current news item using .find() instead of using its class to target it
$(this).find('.news_img').stop(true).animate({
height: 'toggle'
}, 290);
//find the image element within the current news
var $img = $(this).find('.imgswap img');
//if the current event is mouseenter then show the hover image else the src image
//the hover handler registers 2 handler one for mouseenter another for mouseleave
$img.attr('src', $img.data(e.type == 'mouseenter' ? 'hover' : 'src'));
});
//when we leaves the news elements we need to put back the original src, so store it using data api
$('.news .imgswap img').each(function () {
$(this).data('src', this.src);
})
});
Combine your jQuery calls into one function family. Instead of 4 separate .hover() calls, use class names and do the following:
$(document).ready(function () {
$(".news").hover(function(){
$(this).find(".news_img").animate({
height: "toggle"
}, 290, function(){
});
});
});
On your CSS, you're pretty compact already and there's really not much more you can do to reduce the amount of code you have.
Updated fiddle
Use attribute selector in jquery.
$(document).ready(function () {
$("[id^=news]").hover(function () {
$('#news_img').stop().animate({
height: 'toggle'
}, 290, function () {
});
});
});
Fiddle

Expanding content areas using jQuery animate function

I'm using the animate function in jQuery to re-size a content area when the user hovers over the element.
The script works fine but I cant work out how to stop the script from resizing more than once if the element is hovered over more than once.
I have created a jsfiddle here I have also added the js I used.
var minheight = $('.section-fade').css("height");
$('.section-fade').hover(
function () {
$(this).animate({
height: $('.childsection').height()
}, 1000);
},
function () {
$(this).animate({
height: minheight
}, 1000);
});
Any ideas would be very much welcomed.
Cheers
What you're looking for is .stop().
.stop() will cancel all animations on an object.
http://jsfiddle.net/zxm9S/1/
var minheight = $('.section-fade').css("height");
$('.section-fade').hover(
function () {
$(this).stop().animate({
height: $('.childsection').height()
}, 1000);
},
function () {
$(this).stop().animate({
height: minheight
}, 1000);
});

Pass Parameter to jQuery function

I'm using jQuery Tools (http://jquerytools.org/) and cannot get the below function to accept a passed parameter. I'm not proficient in javascript or jquery and cannot find a solution anywhere that will make this work for the below code. Thank you for any help!
Current setup:
<a href='javascript:popup();'>Text Link That Calls Below Function</a>
<script>
function popup() {
if ($("#facebox").hasClass("init")) {
$("#facebox").overlay().load();
}
else {
$("#facebox").addClass("init");
$("#facebox").overlay({
// custom top position
top: 260,
mask: { color: '#838383',
loadSpeed: 200,
opacity: 0.5
},
closeOnClick: true,
load: true
});
}
}
</script>
I would like it to do something like this...
<a href='javascript:popup(apples);'>Text Link That Calls Below Function</a>
<script>
function popup(choosebox) {
if ($("#choosebox").hasClass("init")) {
$("#choosebox").overlay().load();
}
else {
$("#choosebox").addClass("init");
$("#choosebox").overlay({
// custom top position
top: 260,
mask: { color: '#838383',
loadSpeed: 200,
opacity: 0.5
},
closeOnClick: true,
load: true
});
}
}
</script>
You need to pass a string as an arguement, unless you have a variable named apple defined above (var apples; ). Try changing it like below,
<a href='javascript:popup("apples");'>Text Link That Calls Below Function</a>
Note the quotes surrounding the popup("apples")
Since you are using jQuery, you can do it nicely like below,
HTML:
<a href='javascript:void(0)' class="aLink" >Text Link That Calls Below Function</a>
JS:
$(function () {
$('.aLink').click(function () {
popup("apples");
});
});
Also I think you may need to change your selector like below,
function popup(choosebox) {
var $choosebox = $("#" + choosebox);
if ($choosebox.hasClass("init")) {
$choosebox.overlay().load();
}
else {
$choosebox.addClass("init");
$choosebox.overlay({
//..rest of your code
The unobtrusive javascript approach is generally considered better and the JQuery way.
$('a.someclass').click(function() { popup('orange'); });
Providing you give your <a> element has a class of "someclass" in this example.
This keeps your js seperate from your html. That code could go in document ready event:
$(document).ready(function() {
// code here
});
Write a click event for a class on that anchor, then determine which "box" is related to that link by reading a data- attribute. This will give you a generic, reusable block of jQuery code that can be called by any anchor tag matching this pattern.
HTML:
Text Link That Calls Below Function
JavaScript:
$(document).ready(function(){
$('a.popup').on('click', function(e){
var $_target = $('#' + $(this).data("choosebox"));
if ($_target.hasClass("init"){
$_target.overlay().load();
} else {
$_target.overlay().load({
top: 260,
mask: { color: '#838383',
loadSpeed: 200,
opacity: 0.5 },
closeOnClick: true,
load: true
});
}
e.preventDefault();
});
});
​

jQuery fadein fadeout text

I have this at the moment: (the list is longer, but this is just one element)
<a href="Products.aspx"
onmouseover="onMouseOverCatDisplay("H5032.jpg", "Go to: cars");"
onmouseout="onMouseOverCatDisplay("DSC_0414_SS.jpg", "You see: bike");">Car</a>
and above the html, I have this javascript:
<script type="text/javascript" language="javascript">
// <![CDATA[
function onMouseOverCatDisplay(catimg, catnaam)
{
$("#lh").stop().animate({ color: "#1C1C1C" }, 2000);
$("#lh").html(catnaam);
$("#lh").stop().animate({ color: "#DBDBD6" }, 2000);
$("#imgCat").attr("src", catimg);
}
// ]]>
</script>
and this:
<h4 id="lh">Bikes</h4>
<img id="imgCat" src="img/bike.jpg" />
now everything works fine, but the animation does not work.
I'd like to fade out the h4, replace the text and then fade back in.
EDIT set the image source also with jQuery instead of javascript
EDIT2
rewritten the part so that it didn't use the mouseout and mouseover to trigger the javascript. but can't figure out a way to pass another paramter to the jquery (the image)
<script type="text/javascript">
$(document).ready(function () {
$('div.divLeftCatMenu a').hover(
function () {
$(this).stop().animate({ color: '#E90E65', borderBottomColor: '#E90E65' }, 1000);
var catn = $(this).attr('title');
$("#lh").html(catn);
},
function () {
$(this).stop().animate({ color: '#CCC6C6', borderBottomColor: '#3e3e3e' }, 1000);
var catn = $("a.subCatLinksSelected").attr('title');
$("#lh").html(catn);
});
For starters, you are using jQuery, but attaching the events as inline javascript function calls. Don't do that. Attach your event to your DOM objects inside the document ready jQuery function.
Then you are using "document.getElementById" which is fine, but why not just use a standard jQuery selector to be consistent (which, in turn, will use getElementById for you).
Finally, what's likely happening is that your function is calling two animations at the same time. What you want is the second animation to happen only after the first one is finished. To ensure that, you want to call the first animation, then call the html swap and second animation via a callback function in the first. See the documentation for an example:
http://api.jquery.com/animate/
Finally, while animating the color is fine, you may prefer to use fadeIn and fadeOut instead.
UPDATE:
Also, you have this:
onmouseover="onMouseOverCatDisplay("H5032.jpg", "Go to: cars");"
Try this instead:
onmouseover="onMouseOverCatDisplay('H5032.jpg', 'Go to: cars');"
final Demo : http://jsfiddle.net/VdFD9/
If you would like to do this using title attribute, just modify the below code and set your title attributes as reference links(image links if you would like to).
HTML :
<a class="subCatLinksSelected" href="#" style="cursor:pointer;" title="cars"> cars </a>
<a class="subCatLinksSelected" href="#" style="cursor:pointer;" title="bikes"> bikes</a>
<br />
<br />
<h4 id="lh">Bikes</h4>
<img id="ctl00_ContentPlaceHolder1_men_imgCat" src="http://www.gravatar.com/avatar/6dec5eb240c49d979542d7cef64e9a8d?s=128&d=identicon&r=PG" />
javascript :
var arr = [];
arr[0] = "http://www.gravatar.com/avatar/6dec5eb240c49d979542d7cef64e9a8d?s=128&d=identicon&r=PG";
arr[1] = "http://www.gravatar.com/avatar/e555bd971bc2f4910893cd5b785c30ff?s=128&d=identicon&r=PG";
arr[2] = "http://www.gravatar.com/avatar/54d38793d7a407446999b33b81d607fd?s=128&d=identicon&r=PG";
//for instance i'm using an array to cache your image links
//if you can want these links as your anchor tag "title" attrib just modify the below code
$(document).ready(function() {
var which_image = null; //detect which Image to use
$(".subCatLinksSelected").hover(function() {
var catn = $(this).attr('title');
if(catn == 'cars') {
which_image = arr[1];
} else {
which_image = arr[2];
}
onMouseOverCatDisplay(which_image, 'Go to: ' + catn,'#0099f9');
},function() {
var catn = $("a.subCatLinksSelected").first().attr('title');
which_image = arr[0]
onMouseOverCatDisplay(which_image,'You see: ' + catn, '#000');
});
});
function onMouseOverCatDisplay(catimg, catnaam, color) {
$('#ctl00_ContentPlaceHolder1_men_imgCat').attr('src',catimg);
$("#lh")
.css({opacity:0.2,color:"#1c1c1c"})
.html(catnaam)
.css({color: color})
.stop()
.animate({opacity:1 },2000);
}
Did you try
$("#lh").stop().animate({ color: "#1C1C1C" }, 2000, function() {
$("#lh").html(catnaam);
$("#lh").stop().animate({ color: "#DBDBD6" }, 2000);
});
Because I think the two animations are overlapping eachother. This way the second one will start after the first one is finished.
$(document).ready(function () {
$('div.divLeftCatMenu a').hover(
function () {
$(this).stop().animate({ color: '#E90E65', borderBottomColor: '#E90E65' }, 1000);
var catn = $(this).attr('title');
$("#lh").html(catn);
},
function () {
$(this).stop().animate({ color: '#CCC6C6', borderBottomColor: '#3e3e3e' }, 1000);
var catn = $("a.subCatLinksSelected").attr('title');
$("#lh").html(catn);
});
Should work, however, if you want to access the image you'll need to bind it to each function... try this:
$(document).ready(function () {
$('div.divLeftCatMenu a').hover(
function () {
$(this).stop().animate({ color: '#E90E65', borderBottomColor: '#E90E65' }, 1000);
var catn = $(this).attr('title');
$("#lh").html(catn);
}.bind($(some selector for your image)),
function () {
$(this).stop().animate({ color: '#CCC6C6', borderBottomColor: '#3e3e3e' }, 1000);
var catn = $("a.subCatLinksSelected").attr('title');
$("#lh").html(catn);
}.bind($(some selector for your image)));
You'll then be able to access the image in each function using this, like this.src

Categories