jQuery Hide using ID - javascript

I'm trying to change the border color of an image using its id with jquery
( photo['id'] is passed in from a previous function )
the ids of the photos are of the form 'photo239839'
$('#photo'+photo['id']+'').click(function(){
$('#photo'+photo['id']+'').css('border-color','#777');
});
When I try to use this same code using its class it works,
but I can't use this method since there are multiple images on the same
page with the same class
$('img.flickr_photo').click(function() {
$("this.flickr_photo").css('border-color','#777');
});

This is what you need to do:
$('img.flickr_photo').click(function(){
$(this).css('border-color','#777');
});

I would always always add a css class rather than an inline style.
Much more maintainable and extensible.
Example:
$('img.flickr_photo').click(function(){
$(this).addClass('greyishBorder');
});

Either photo['id'] is wrong, or is changing after you set up the click handler.
To test for the first case, you can alert (or console.log with FireBug, or whatever) the length of the jQuery selection:
alert($('#photo'+photo['id']).length);
The solution in the second case is to use 'this'. In the click handler, 'this' is set to the element that caused the click event.
$('#photo'+photo['id']).click(function(){
$(this).css('border-color','#777');
});
Edit: #Dreas Grech is right, as long as you want to apply the behavior to all the elements with the flickr_photo class. If you can generalize the selector to select all the elements with a single query, it's better to do that.

Related

jQuery if data-id element hasClass not working

I don't know if the function i am trying to create is missing an element or if I am missing something but my function isn't working at all. Not sure if am missing something or if i am not adding something. let me know I provided jQuery and screenshot of the code i am trying to get to work. Basically what i am trying to do is if a certain element that has a data-id has a certain class then hide certain list-items.
$(function($){
if( $('.chbs-vehicle[data-id="313"] a').hasClass('chbs-state-selected') ){
$('ul.chbs-list-reset li(1)').hide();
}
});
li(1) isn't a valid expression and you should use a different evaluator:
$('ul.chbs-list-reset li:eq(0)')
$('ul.chbs-list-reset li:first-child')
$('ul.chbs-list-reset li').eq(0)
Take a look at this Demo
If your condition is met on page load, it works just fine. However, if the chbs-state-selected class is added dynamically, you need to listen for that change with an event handler. Your script as you have it doesn't constantly poll the document to see if Vehicle 313's a has the class.
Based on your comment, it sounds like you need to listen for that same click event that adds the chbs-state-selected class. Check out this rudimentary Demo.
Given this, you don't necessarily need to check for the class, just attach the hide/show functions to the same event. However, if necessary you can add the hasClass check to it.
Regardless, it should be inside that same handler that adds the chbs-state-selected in the first place
You can use eq: jquery function
$(function($){
if( $('.chbs-vehicle[data-id="313"] a').hasClass('chbs-state-selected') ){
$('ul.chbs-list-reset li:eq(0)').hide();
}
});

How to set jQuery mouseleave function for multiple divs with same id

I have a site that has multiple divs with the same id name. I want to set a mouseleave function for all of the divs that have this id. In my $(document).ready function I have this code...
$('#my_post_container').mouseleave(function(e)
{
hideSnippet();
});
My hideSnippet() function is correct, but doing this only set the mouseleave function for the first time that a div comes up of id my_post_container. Is there a way to set the mouseleave function to all divs with this id?
I have a site that has multiple divs with the same id name.
Then you need to fix that. You must not have more than one element with the same id. id values must be unique on the page.
You probably want to use class instead, at which point your code is basically fine:
$('.my_post_container').mouseleave(function(e)
{
hideSnippet();
});
...although it coudl be shortened a bit if hideSnippet doesn't care what arguments it gets, doesn't care about this, and doesn't return false:
$('.my_post_container').mouseleave(hideSnippet);
It is invalid HTML to have multiple objects with the same id. As such, you cannot use normal selectors to find them all and you should fix your HTML to not do that.
The #1 suggestion is to fix the HTML so it does not have multiple objects with the same ID. Use a class name and you can then select them all with getElementsByClassName() or querySelectorAll() or with jQuery selectors as in:
$('.my_post_container')
If you insist on having multiple objects with the same id (a bad choice), then you will have to somewhat manually iterate over all possible objects that could have that id.
$("div[id='my_post_container']");
But, this is pretty darn inefficient because the browser can't use any of the built-in selector engine logic and it could break in the future if jQuery decides to optimize this. You really ought to switch to using class names.
You can not have multiple elements on the same page with the same id. Use a class instead, as shown here:
HTML:
<div class="my_post_container">...</div>
<div class="my_post_container">...</div>
<div class="my_post_container">...</div>
jQuery:
$('.my_post_container').mouseleave(function(e)
{
hideSnippet();
});
First of all there should not be any div elements with same ID name.. first we should solve that by keeping class name same.
then on mouse leave and enter part..
$(".testClass").on({
mouseenter : function() {
$(this).css({"background-color" : "blue"});
},
mouseleave : function() {
$(this).css({"background-color" : "green"});
}
});
this should work.. will add a js sample http://jsfiddle.net/meVc6/
and the same thing can be achived using css too..
just add css .testClass:hover { background-color:blue}

jQuery add class based on CSS characteristics

I am looking for a method with jQuery (or plain JS) in which to build a conditional on whether a div has a specific CSS characteristic.
For example, I want jQuery to add position:fixed to an element's CSS when another element is set to display:none, though change back to position:relative on the first element when the second element changes to display:block.
Any ideas?
If your change is event driven you just add the code to your event handlers
so if element one is made hidden by a click - make element 2 position fixed
$("#element_one").click(function(){
$("#element_one").hide();
$("#element_two").css({"position":"fixed"});
})
if you just want to watch elements you will need timers (although I cannot really imagine a scenario where you do not trigger the change by either an event of programaticaly)
watchInterval = setInterval("watchMe()",10)
function watchMe(){
if ($("element_one").is(":hidden") ) {
$("#element_two").css({"position":"fixed"});
}
}
$('#elOne').css('display') == 'none' ? $('#elAnother').css({'position':'fixed'}) : $('#elAnother').css({'position':'relative'});
Would that do the trick?
or perhaps :
$('#elOne').is(':hidden') ? $('#elAnother').css({'position':'fixed'}) : $('#elAnother').css({'position':'relative'});
There's not any nice way of doing this as you cannot "spy" on CSS changes, though jQuery does have a watch plugn which can monitor changes on certain properties. Your best bet is to use getComputedStyle which will get the real CSS values used for any object and act accordingly.

Recursive jQuery function to amend select option values

I have a form that I am trying to alter with jQuery. Basically, my form has two elements and I need to change the value of the first option in each of them. However, there is an "add more" option that uses AJAX to dynamically generate another element that also needs changed. This add more button can be clicked an unlimited amount of times.
Right now I have this:
$(document).ready(function(){
$("#myname-0-field option:first").val("None");
$("#myname-1-field option:first").val("None");
});
This works fine, but once the "add more" button is clicked, I have more elements called "#myname-2-field", "#myname-3-field", "#myname-4-field" etc. These obviously aren't affected by adding another line into my jQuery as the document has already loaded when they are added.
So the real question is, can someone point me in the right direction of writing a function that can react when the new element is added and change it. If possible, I'm also looking for the function to be aware and look for "#myname-X-field option:first" for tidyness.
use live() function
Then using each function set value
From the jQuery API look live function
Maybe you could add class to your element, so that finding particular element would be easier and it would not add event to other similar elements.
In the example I have a Li with class
$('li.myClass').live('click', function() {
$(this).val(); // this is the getter for clicked value
$(this).val("some_value_here"); // this is the setter for clicked value
});
Now you can add more elements (that has myClass class) and it will have a click event.
Btw. if you know that all elements are inside some container (div for example) then you can write more efficient jQuery using delegate.
$('#container_id').delegate('li.myClass', 'click', function () {
});
This is more efficient because it looks your new elements only under "containter" not from the whole DOM structure.

JQuery event selector

Say i have 10 small images that i want to use as tooltips.
Im assinging them all the same class, '.helper'
Im selecting helper, then calling
mouseenter(function() { $(".helper").stop(false,true).fadeIn(); })
I then want a div to popup, containing some text. This works fine if there's only one tooltip on the page, but as soon as there is more than one, whenever i hover over one, they all appear at the same time.
Have i got something fundamentally wrong?
Comments appreciated.
Thx
Use this as the selector inside instead of the .helper selector again:
$('.helper').mouseenter(function() {
// "this" now refers to the image that is being hovered...
$(this).stop(false, true).fadeIn();
});
If you're wondering what the problem was, it was that when you called
$(".helper")
within your function, you were getting all the elements with class helper, in stead of just the single element you wanted.

Categories