Newbie in javascript.. Need a little help.
I have a SPAN or IMG that I want to fadeOut using javascript. However nothing happens when I do this:
// HTML
<span id='test_one'>Span Text Here</span>
<img src='img_src_here' id='test_two'>
// JavaScript
$(test_one).fadeOut();
$(test_two).fadeOut();
But if I do this, it functions correctly:
// HTML
<div id='test_one'>Span Text Here</div>
// JavaScript
$(test_one).fadeOut();
Am I just making or a silly mistake or am I going insane?
ThanksCoulton
Assuming you're using jQuery, your selector is incorrect:
$('#test_one').fadeOut();
Note that it should be a string (so single or double quotes) and use '#' to select by id. Documentation of selectors can be found on the jQuery site.
This should work:
// HTML
<span id='test_one'>Span Text Here</span>
<img src='img_src_here' id='test_two'>
// JavaScript
$('#test_one').fadeOut();
$('#test_two').fadeOut();
Edit
As to why it works with the div but not the img or span, I'm not entirely clear but as #Steve pointed out, it is possible to reference elements by using their ids as global variables. However, this is non-standard behaviour and only some browsers (notoriously IE) perform this mapping of element ids to the global namespace. IE also allows fetching of named elements via getElementById()! See this and this. I would suggest not depending on this behaviour.
Firstly, which library are you using? jQuery? (The fadeOut() method is not built in to JavaScript.)
Try setting the CSS property of your <span> or <img> to display: block or display:inline-block. This should make the fade out work. The reason it works on your <div> element is that it is a block element by default. <span> and <img> elements are displayed inline by default.
You must use the selectors efficiently like this
for "id" use:
$('#myId').fadeOut();
for classes like this:
$('.myClass').fadeOut();
and so on....
In your styles add this:
span#test_one { display:inline-block; }
And of course:
$("#test_one").fadeOut();
The code you've provided will work only in IE.
I would call it a stupid mistake (we all make them), your selector should be $('#test_two')
Look at: http://jsfiddle.net/ku8sa/
Related
I use span elements like button and I disable and enable it depending on bussnies condition using old JS code like this:
document.getElementById('lblChecks').disabled = false/true
in HTML
<span id="lblChecks" disabled="disabled" class="GridHeader" onclick="ChecksPoPuP();" style="display:inline-block;color:White;height:19px;width:132px;cursor: hand;">Cheques</span>
In CSS I use .GridHeader[disabled="disabled"] but it doesn't work on chrome, but it works fine on IE.
So how can I filter (.disabled) as dynamic property in CSS
Note: the problem can be solved easily using addClass and removeClass in JQuery but I have a lot of files and its hard to replace all of them
You can define a common class name for all the elements which is disabled/enabled back and forth, and use CSS to style it.
For example:
.att-disabled:disabled{ // style goes here }
Refer more:
https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled
I want to toggle(hide/show) an element when a button is being pressed. I have two ways as to implement this:
Find the element according to its class name, e.g $('.my-content')
Find the element according to its relevant DOM position towards the button, e.g. $('#my-button').parent().next().next().next()
However, none of the above seems to me very reliable since in case someone changes the HTML code, the above approaches should not work. Is there something more reliable I am missing?
If it's a specific element, supply it with an Id value and use that
to find it.
If it's a TYPE of element, use a class name.
Other than that, there's no real conventions. Just try and make sure that somebody reading your code understands what is going on.
A very good practice is to decouple HTML, CSS and JS.
When binding javascript to DOM elements you should use javascript selectors.
Basically classes with some custom prefix (like js-) which will be used only for javascript purposes (not css style).
So whenever the DOM tree structure or the CSS class names are changed, you can still have your working JS selector
HTML
<div class="my-content js-toggle-element"></div>
JS
$('.js-toggle-element')
CSS
.my-content{ ... }
Plus, using Javascript Selectors:
makes HTML highly readable: you can easily find out what will happen to that element with that js class
allows you to easily apply/disapply that behaviour also to other elements in the future, simply by adding/removing that class in your HTML and without affecting CSS at all
<div class="my-content js-toggle-element"></div>
...
<div class="another-content-to-toggle js-toggle-element"></div>
Using jQuery will be much easiest way. Like this -
$( ".target" ).toggle();
The matched elements will be revealed or hidden immediately, with no animation, by changing the CSS display property. If the element is initially displayed, it will be hidden; if hidden, it will be shown.
Reference - jQuery Toggle
If the class or the position of the element in DOM is changing then you can try
selecting it with the inner text
$("button:contains('buttontextgoeshere')")
I have this element in my HTML page:
<a style="display:block;width:728px;height:90px;margin:0 auto;background:#EEE url('/_images/2011images/img_dotco_3.jpg') no-repeat top left; text-decoration:none;color:#000;" href="/domain-registration/dotco-overview.aspx?sourceid=bnrq2co728x90">
<span style="float:right;margin:5px 27px 0 0;width:110px;color:#FFF;text-align:center">
<span style="display:block;font-size:1em;text-align:center">NOW ONLY</span>
<strong style="display:block;font-size:1.6em;text-align:center"><!-- START TAG // Co_RegisterPrice_TLD -->
<span class="Tag_Co_RegisterPrice_TLD"><strong>$35.70</strong>/yr</span>
<!-- End TAG // Co_RegisterPrice_TLD --></strong>
</span>
</a>
I need to hide it with CSS or Javascript. CSS would be the best scenario but Javascript is OK as well.
The fact is that I cannot edit the HTML code at all, so I have no way to delete this item directly. Also this is not parent of any other HTML element, so I do not find an easy way to hide it with CSS.
Also I need to hide this A element even if the background image changes or the link changes, in fact it's not always the same.
I reported all the available HTML.
Here is an example http://subdir.co/help-center/default.aspx
It's the top banner there.
Let me know how to hide it from the page. Thanks.
Try with jQuery:
$('a[href^="/domain-registration/dotco-overview.aspx?sourceid"]').hide();
This hides the a tag with a href attribute starting with /domain-registration/dotco-overview.aspx?sourceid.
Use:
document.getElementById('yourElementId').display=none;
You can traverse the dom tree from the class "Tag_Co_RegisterPrice_TLD" to find the A tag which you can then hide.
If you need to do additional logic then you can access the text (e.g. price/title/url) before deciding to hide.
Use jQuery if raw javascript is to much for you.
Since you cannot change the HTML code, you can't add an identifier to the element in order to select and manipulate it.
But you can use jQuery to select the first 'a' element, and set the 'display' property to 'none'.
I think something like this should do:
$('a:first').css("display","none");
You could try it with css:
a[style][href] {
display: none !important;
}
i think adding class or making some rule for css selector woudn't work, because definition in attribute of the elements overrides another style definition.
It will be easy if you use some javascript library for dom manipulating for example jQuery.
after that you can write something like
$(".sCntSub3 > a").hide()
you can try finding element from browser console. It is easy way how to verify you choose right element
jsFiddle Classname Method DEMO
jQuery via Classname: In this method we "look inside" the anchor for clues.
$(document).ready(function () {
// To disable the line below, just comment it out just like this line is.
$('.Tag_Co_RegisterPrice_TLD').closest('a').hide();
});
jsFiddle ID Method DEMO
jQuery via ID: This time, we don't look inside since anything can change. We now use a div reference!
$(document).ready(function () {
// To disable the line below, just comment it out just like this line is.
// No matter the unique ID code in front of MasterUpdatePanel Div, it will always be matched.
$('[id$="MasterUpdatePanel"]').next('a').hide();
});
Shown here is a Firefox Screenshot of the HTML Page. Notice the Div ID contains ctl00_MasterUpdatePanel. The letters, numbers, and underscore in front of that may change, but not this keyword. Therefore, a match of the "ending part" of the id works!
I'm experimenting with a third party library written on top of jQuery.
I noticed, for a number of their widgets, that when your source says, for example,
<div id="myWidgetInst" class="their-widget-class-0" ... </div>
Firebug shows that the resulting DOM element reads:
<div id="myWidgetInst" class="their-widget-class-0 their-widget-class-1 ..." ... </div>
How do they do it? Many thanks.
it's probably jquery !
there's probably a function running adding classes to the elements
Not sure I fully understand your question but when looking at the "regular" source of the website, this source doesn't show any modifications to the DOM that happened due to javascript modifications. Firebug does show these updates.
using jQuery, you can add/remove classes simply by using .addClass("className") or .removeClass("className") function on the element you want to modify
They would add classes to the element with jQuery. For example, if the plugin's purpose was to hide all elements on the page (innovative and highly practical, I know), they could use the following:
$(document).ready(function() {
$("*").addClass("my-widget-made-your-element-invisible");
});
With the CSS:
.my-widget-made-your-element-invisible { display: none; }
The methods in which you can manipulate the class attribute in jQuery include the following:
$("#elem").addClass("a"); // adds the class "a" to elem
$("#elem").removeClass("a"); // removes the class "a" from elem
$("#elem").attr("class", "a"); // gives elem a complete class of "a"
$("#elem").attr("class", ""); // removes all classes from attribute
I have a div with id #test that contains lots of html, including some youtube-embeds etc.
Somewhere in this div there is this text: "[test]"
I need to replace that text with "(works!)".
The normal way of doing this would of course be:
document.getElementById("test").innerHTML = document.getElementById("test").replace("[test]","(works!)");
But the problem is that if i do that the youtube-embeds will reload, which is not acceptable.
Is there a way to do this?
You will have to target the specific elements rather than the parent block. Since the DOM is changing the videos are repainted to the DOM.
Maybe TextNode (textContent) will help you, MSDN documentation IE9, other browsers also should support it
Change your page so that
[test]
becomes
<span id="replace-me">[test]</span>
now use the following js to find and change it
document.getElementById('replace-me').text = '(works!)';
If you need to change more than one place, then use a class instead of an id and use document.getElementsByClassName and iterate over the returned elements and change them one by one.
Alternatively, you can use jQuery and do it even simpler like this:
$('#replace-me').text('(works!)');
Now for this single replacement using jQuery is probably overkill, but if you need to change multiple places (by class name), jQuery would definitely come in handy :)