document.getElementById() alternative in jQuery - javascript

UPDATE: I'm sorry that my thread was misinterpreted by many users. I'll try to be more clear.
I'm using Drupal and I have created three floating banners. On the frontpage there is a block (block1) that displays one floating banner and after refresh the second one is appearing and for the third too.
Like a wrote before these banners has a little X button to stop overflow.
I've putted this script in a one of the banners and it's working great.
<script language="javascript">
function doexpand() {
document.getElementById("block1").style.overflow = "visible";
}
function dolittle() {
document.getElementById("block1").style.overflow = "hidden";
}
</script>
The real problem is that in categories pages I have #block2 and in articles #block3.
These block are displaying the same banners. The code over is working only for a one ID. In this case #block1. document.getElementById is not working for more ID's as I read from other topics.
I've tried with jQuery with two blocks idents like this:
(function ($) {
function doexpand() {
$("#block1,#block2").css("overflow","visible");
}
function dolittle() {
$("#block1,#block2").css("overflow","hidden");
}
})(jQuery);
It's not working.
The firebug/console displays: ReferenceError: doexpand is not defined.
I've tried with a single block too with jQuery like this:
(function ($) {
function doexpand() {
$("#block1").css("overflow","visible");
}
function dolittle() {
$("#block1").css("overflow","hidden");
}
})(jQuery);
and it's displaying the same error.
Note: Drupal has a different wrapping and it's like this:
(function ($) {
//your existing code
})(jQuery);

Please have a look on jQuery Selectors.
I think in your case, it is better to apply style with help of css for multiple elements. e.g. :
<script language="javascript">
function doexpand() {
$('.block').style.overflow="visible";
}
function dolittle() {
$('.block').style.overflow="hidden" ;
}
</script>
Please add class="block" to all of blocks for which you want to apply this style/function, it will apply on all of the blocks having css class "block".

jQuery?
HTML:
<div class="block2"></div>
JS:
function doExpand(selector) {
if ( $(selector).length ) {
$(selector).css({'overflow':'visible'});
}
}
Calling with non ID selector would look like this: (jQuery syntax):
doExpand('.block2');

The above code is perfectly valid in jQuery (which is a JavaScript library).
If you want to use a more typical jQuery code, you can do
$('#block1').css('overflow', 'visible');
You can expend it to multiple id like this :
$('#block1, #block2').css('overflow', 'visible');
You always can get the DOM object from a jQuery object, which means you could also have adapted your code to use jQuery selectors using
$('#block1').get(0).style.overflow="visible";
(this specific example isn't smart : no need to use jQuery if you don't use a complex selector or jQuery functions)

Pretty simple really, jQuery selection is based on css selectors for the most part. These selectors are then translated into an array of dom objects held in a jQuery object.
function doexpand() {
$("#block1").css("overflow","visible");
}
function dolittle() {
$("#block1").css("overflow","hidden");
}

You should never have more than one HTML element with the same ID (Which is why document.getElementById only returns one element)
You can just refeerence block2, block3 directly document.getElementById("block2").style.overflow="hidden" ;
Or use getElementByClassName
var elements = document.getElementsByClassName("yourClass")
Which will pick up all elements with a specific class.
If you want to use jQuery like the other answers are suggesting you can match on the element name. For example:
$('div[id^="block"]').css("overflow", "visible");
This will match all div element where their ID starts with block. You can also use other wildcards such as * for contains and $ for ends with.

Here is your Javascript Code in jQuery. I dont understand what you want do do, but you could pass the params in the function. Example under this code.
<script language="javascript">
function doexpand() {
$("#block1").css({'overflow': 'visible'});
}
function dolittle() {
$("#block1").css({'overflow': 'hidden'});
}
</script>
Here is it
<script language="javascript">
function doexpand(element) {
$("#" + element).css({'overflow': 'visible'});
}
function dolittle(element) {
$("#" + element).css({'overflow': 'hidden'});
}
</script>
Than you could call it like: doexpand("theIDofTheElement");

Alternative to document.getElementById("an_element);
in Jquery is: $("#an_element");
It will work fine in JQuery, it's just that JQuery makes things faster and less verbose.

Related

load jquery function before content

i made this function:
var jq111 = jQuery.noConflict();
if (jq111("#tab-upsell_tab").find("div").length > 0){
} else {
jq111(".upsell_tab_tab").hide();
jq111("#tab-upsell_tab").hide();
}
This hide a element if are empty.
But on page load, #tab-upsell_tab appear for 1 second (if need to be hide) and i don't like it.
There is a way to load this function before this element? Or something similiar.
Edit: i accept a css solution, but how?
You should set .upsell_tab_tab and #tab-upsell_tab to display: none in your CSS. Change your JavaScript to this also:
var jq111 = jQuery.noConflict();
if (jq111("#tab-upsell_tab").find("div").length > 0){
jq111(".upsell_tab_tab").show();
jq111("#tab-upsell_tab").show();
}
This way your elements are hidden by default, and you must imperatively show them based on your logic.
Try using $.holdReady() , .ready()
$(window).load(function() {
var jq111 = jQuery.noConflict();
jq111.holdReady(true);
if (jq111("#tab-upsell_tab").find("div").length > 0) {
} else {
jq111(".upsell_tab_tab").hide();
jq111("#tab-upsell_tab").hide();
}
jq111.holdReady(false);
jq111(document).ready(function() {
// do stuff
})
})
div .length within "#tab-upsell_tab" not greater than 0
http://plnkr.co/edit/Xp2RbPe65BaFeobtTVOL?p=preview
div .length within "#tab-upsell_tab" greater than 0
http://plnkr.co/edit/ekSUelSinlM8baKQe74Y?p=preview
The DOM renders HTML, CSS, then JS. So if you want your HTML elements hidden then hide them with your CSS or you could create using a template system like mustache or in your JS code. I prefer creating them in your JS code. It makes your code cleaner and it lighter on the DOM.

Unhiding search result div with javascript or jquery without button click

I'm very frustrated right now... and making lots of mistakes. Sorry about that
I've been trying to unhide a specific div based on search results
If no search was made the div should not appear, and this is easy with css, but once the search is done I have to change the style to 'block'.
Since I'm using the google custom search javascript its too hard to replace the button for another similar button that triggers my javascript function.
I also couldn't figure out how to replace the "resultDiv" into some more complex path
I already done this javascript function to hide a div based on the result div...
css div style is at #main.section .widget.HTML
function check()
{
if (document.getElementById('resultDiv')) {
if ($('.gsc-expansionArea').is(":empty")) {
document.getElementById('resultDiv').style.display = 'none';
}
else {
document.getElementById('resultDiv').style.display = 'block';
}
}
}
I think there might be 2 possible solutions. First is to load the script
<body onLoad="check();">
but doesn't seems to work.
Second would be check URL for ?q= meaning a search was done, but I don't know how to get these parameters from URL.
Please assist me. Thank you
well, since you've tagged jquery:
$(window).load(function(){
check();
})
and your function check() could be more like
function check() {
if ($('#resultDiv').length) {
if ($('.gsc-expansionArea').is(":empty")) {
$('#resultDiv').css({'display': 'none'})
}
else {
$('#resultDiv').css({'display': 'block'})
}
}
}
--
Second would be check URL for ?q= meaning a search was done, but I
don't know how to get these parameters from URL.
use location.search
Location search Property
MDN window.location
Replace
<body onLoad="javascript:check();">
with
<body onLoad="check();">
You can use
$(document).ready(function()
{
check();
}
to load the function when the page loads. You can also simplify your function with jQuery:
function check()
{
var isEmpty= $('.gsc-expansionArea').is(":empty");
$('#resultDiv').toggle(isEmpty);
}
The documentation for toggle is here.

Writing javascript with jquery and using a variable

As a javascript newbie, I am struggling to use a script with a variable that runs a bit of JQuery (and also struggling to use the right language here, I'm sure!)
The action I want to happen is to change the CSS class of a specific div, e.g. #det90, for which I have the following code (I have used the same on a $(window).load(function() and it works on a different set of divs):
$("#MYDIVIDHERE").switchClass("sdeth","sdet",50);
So I wrote the following:
<script type="text/javascript">
$(function revealCode(divID) {
$("#divID").switchClass("sdeth","sdet",50);
})
</script>
and called it from an anchor with:
onClick="revealCode('det90');"
I think the problem is that I don't know how to write the script and pass the variable in the brackets (divID) to the next line (where I've got "#divID"). Any help or pointers to tutorials gratefully received!
Solution
Thanks to all, but particularly to Caleb. I've scrapped the general function and the onClick, added an ID to the anchor and inserted the following for that anchor (and then repeated that for each anchor/div combination I want to use it on ... and it works :D
$("#linkID").click(function() {
$("#divID").switchClass("sdeth","sdet",50);
});
Change your code to: onClick="revealCode('#det90');"
$(function revealCode(selector) {
$(selector).switchClass("sdeth","sdet",50);
})
jQuery is powered by "selectors" -- similar to CSS syntax.
Don't quote your variable name. Just quote the "#" prefix.
<script type="text/javascript">
$(function revealCode(divID) {
$("#" + divID).switchClass("sdeth","sdet",50);
})
</script>
Change to:
<script type="text/javascript">
function revealCode(divID) {
$("#" + divID).switchClass("sdeth","sdet",50);
}
</script>
You don't need $() around the function
$("#divID") will look for an element with the ID divID, and not what was specified in your function parameter
This won't work. revealCode is local to that scope and not known outside. Also, you're not using the argument you've passed into your handler.
If you're using jQuery, use it to bind to the handler as well like this:
jQuery(document).ready(function() {
function revealCode(divID) {
$("#" + divID).switchClass("sdeth","sdet",50);
}
jQuery("#divID").click(function() {
revealCode('det90');
});
});
Move your onclick event handler attachment into javascript code. You should try not to mix your functional code with your html.
Anonymous version:
$('#myDiv').click(function () {
$(this).switchClass("sdeth","sdet",50);
});
Normal version:
var myFunction = function (element) {
$(element).switchClass("sdeth","sdet",50);
};
$('#myDiv').click(myFunction, {element: this});

jquery and javascript conflict

I am using jquery in the master page and javascript in the content page. When Jquery is used alone it works fine. But when I use the javascript(content page) along with jquery(master page) then jquery in master page stops working.
master page script
$(document).ready(function() {
// set up the accordion
$("#accordion>h3").click(function() {
$(this).next("div").slideToggle(500).siblings("div").slideUp(500);
});
// show active menu section
setTimeout('$("#accordion>div.activesec").slideToggle(800)', 100);
});
content page script
$('slideshow').style.display = 'none';
$('wrapper').style.display = 'block';
var slideshow = new TINY.slideshow("slideshow");
window.onload = function () {
slideshow.auto = true;
slideshow.speed = 5;
slideshow.link = "linkhover";
slideshow.info = "information";
slideshow.thumbs = "slider";
slideshow.left = "slideleft";
slideshow.right = "slideright";
slideshow.scrollSpeed = 4;
slideshow.spacing = 5;
slideshow.active = "#fff";
slideshow.init("slideshow", "image", "imgprev", "imgnext", "imglink");
}
I believe the collision is caused by your use of the $ shorthand in the content page. $ is used to represent jQuery. So, jQuery is trying to interpret $('slideshow').style.display , which is not valid jQuery.
Replace your shorthand with document.getElementById, or use jQuery selectors.
Standard JS
document.getElementById.style.display = 'none';
Or jQuery
$('slideshow').css('display', 'none');
Ok, so it looks like the other script uses $, just like jQuery. You need to use $.noConflict() to prevent namespace clashes:
var $j = jQuery.noConflict();
$j(document).ready(function() {
// set up the accordion
$j("#accordion>h3").click(function() {
$j(this).next("div").slideToggle(500).siblings("div").slideUp(500);
});
// show active menu section
setTimeout('$j("#accordion>div.activesec").slideToggle(800)', 100);
If you don't want to use $j instead of $ in all jQuery functions, you can wrap everything (except the content page scripts!) in a function that assigns $ to jQuery:
(function( $ ){
// everything inside works normally with $
})( jQuery );
it looks like your selections are missing "#" or "." depending on weather your trying to access an id or class
$('#slideshow').style.display = 'none';
$('#wrapper').style.display = 'block';
You are passing a string to the setTimeout parameter. Really bad.
$('slideshow').style.display = 'none';
You are trying to find <slideshow> tags with jQuery, maybe you are missing a class or ID selector?
Also, the style method is not a jQuery method asfar as I know, so maybe you will want to call it on a JavaScript object instead of a jQuery one? Or perhaps use the .css method on it?
Did u put ur plane javascript inside the :
$(document).ready(function() {
});
If yes then try to put them outside it.
Best practice would be to put all your Javascript/Jquery code in a .js file. Then import this .js in the page that need it.
This way your HTML will be clean and not cluttered with javascript all over the place.
I know i don't really answer your problem, but working this way you will probably help avoid it.
good luck

jQuery code critque

Thought I'd post here. My first hour on jQuery, actually first programing ever done. Would love to learn whats not right and how it could be better.
$(function() {
function hide_me()
//A place to specify which elements you want hidden, on page load.
{
$("li.credentials").hide();
}
function first_bow()
//The div right_column takes a bow on initial load.
{
$("div#right-column").show("drop");
}
function bigpeek()
//The third column toggles in/out. All elements under div right_column.
{
$("div#right-column").toggle("drop", "fast");
}
function smallpeek()
//Smaller snippets like credentials or user assignment flying in/out.
{
$("li.credentials").toggle("drop", "fast");
}
$(document).ready(function() {
$("*").ready(hide_me);
$("*").ready(first_bow);
$(".btn-new-email").click(bigpeek);
$(".button").click(smallpeek);
$(".icon-delete").mouseover(function() {
$(this).effect("bounce", "fast");
});
});
});
The best thing to learn about programming is how to effectively re-use code. In your code, you have set up some functions that you yourself claim will do a bunch of the same thing. So instead, you could make it better by only writing code to do the repeated task once.
For one example, instead of creating a function where you place a bunch of things that need to be hidden, I would add a class to the elements that should be hidden, and then hide all those elements:
function hide_me()
//Hides anything with the "hide-me-onload" class
{
$(".hide-me-onload").hide();
}
$(function () {
...
}
is the same as
$(document).ready(function() {
...
}
So you can move the method calls from inside your $(document).ready() to be inside your $(function(){}). Also try to use IDs instead of class names wherever possible. Something like this will go through the entire DOM to look for an element
$(".item")
Be more specific
$("#itemID") // use IDs instead of Classes
//If you have to use class name then you can speed up the selector by adding the element tag before it
$("div.item")
Using $("*").ready() within $(document).ready() is redundant... you already know using all of the elements are ready! Also, in general using the universal selector $('*') is very inefficient.
So, the first two lines of your $(document).ready() can just be:
hide_me();
first_bow();
Other than that and a couple of issues with organization and nomenclature you're off to a great start, keep it up!

Categories

Resources