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});
Related
i have one simple jQuery function, that does not work. I need to write a function that if anyone click on some class called 'modal-opened' it need to add class to body 'modal-open'. So i write function like this:
$(document).ready(function(){
$(".modal-opened").click(function(){
$("body").addClass("modal-open");
});
});
I have that same function in JavaScript that works actually, here it is.
document.getElementById("modal-opened").addEventListener("click", myFunction);
function myFunction() {
$("body").addClass("modal-open");
}
I need that same but in jQuery.
Notice you get modal-opened by ID in plain JS:
// You get modal-opened by ID in plain JS
$(document).ready(function(){
$("#modal-opened").click(function(){
$("body").addClass("modal-open");
});
});
try to do this:
<script>
$(document).on('click','.modal-opened',function(){
$("body").addClass("modal-open");
});
</script>
There is an error in your jQuery code with reference to working javascript code you shared.
document.getElementById("modal-opened") in javascript is equivalent to $("#modal-opened") and not $(".modal-opened").
In jQuery, you can access an element by Id using # and by class using dot.
Hope this helps..
Please share your feedback.
If I have a lot of functions on startup do they all have to be under one single:
$(document).ready(function() {
or can I have multiple such statements?
You can have multiple ones, but it's not always the neatest thing to do. Try not to overuse them, as it will seriously affect readability. Other than that , it's perfectly legal. See the below:
http://www.learningjquery.com/2006/09/multiple-document-ready
Try this out:
$(document).ready(function() {
alert('Hello Tom!');
});
$(document).ready(function() {
alert('Hello Jeff!');
});
$(document).ready(function() {
alert('Hello Dexter!');
});
You'll find that it's equivalent to this, note the order of execution:
$(document).ready(function() {
alert('Hello Tom!');
alert('Hello Jeff!');
alert('Hello Dexter!');
});
It's also worth noting that a function defined within one $(document).ready block cannot be called from another $(document).ready block, I just ran this test:
$(document).ready(function() {
alert('hello1');
function saySomething() {
alert('something');
}
saySomething();
});
$(document).ready(function() {
alert('hello2');
saySomething();
});
output was:
hello1
something
hello2
You can use multiple. But you can also use multiple functions inside one document.ready as well:
$(document).ready(function() {
// Jquery
$('.hide').hide();
$('.test').each(function() {
$(this).fadeIn();
});
// Reqular JS
function test(word) {
alert(word);
}
test('hello!');
});
Yes you can easily have multiple blocks. Just be careful with dependencies between them as the evaluation order might not be what you expect.
Yes it is possible to have multiple $(document).ready() calls. However, I don't think you can know in which way they will be executed. (source)
Yes it is possible but you can better use a div #mydiv and use both
$(document).ready(function(){});
//and
$("#mydiv").ready(function(){});
I think the better way to go is to put switch to named functions (Check this overflow for more on that subject).
That way you can call them from a single event.
Like so:
function firstFunction() {
console.log("first");
}
function secondFunction() {
console.log("second");
}
function thirdFunction() {
console.log("third");
}
That way you can load them in a single ready function.
jQuery(document).on('ready', function(){
firstFunction();
secondFunction();
thirdFunction();
});
This will output the following to your console.log:
first
second
third
This way you can reuse the functions for other events.
jQuery(window).on('resize',function(){
secondFunction();
});
Check this fiddle for working version
Yes you can.
Multiple document ready sections are particularly useful if you have other modules haging off the same page that use it. With the old window.onload=func declaration, every time you specified a function to be called, it replaced the old.
Now all functions specified are queued/stacked (can someone confirm?) regardless of which document ready section they are specified in.
Yes, it's perfectly ok.but avoid doing it without a reason. For example I used it to declare global site rules seperately than indivual pages when my javascript files were generated dynamically but if you just keep doing it over and over it will make it hard to read.
Also you can not access some methods from another
jQuery(function(){}); call
so that's another reason you don't wanna do that.
With the old window.onload though you will replace the old one every time you specified a function.
It's legal, but sometimes it cause undesired behaviour. As an Example I used the MagicSuggest library and added two MagicSuggest inputs in a page of my project and used seperate document ready functions for each initializations of inputs. The very first Input initialization worked, but not the second one and also not giving any error, Second Input didn't show up. So, I always recommend to use one Document Ready Function.
You can even nest document ready functions inside included html files. Here's an example using jquery:
File: test_main.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="main-container">
<h1>test_main.html</h1>
</div>
<script>
$(document).ready( function()
{
console.log( 'test_main.html READY' );
$("#main-container").load("test_embed.html");
} );
</script>
</body>
</html>
File: test_embed.html
<h1>test_embed.html</h1>
<script>
$(document).ready( function()
{
console.log( 'test_embed.html READY' );
} );
</script>
Console output:
test_main.html READY test_main.html:15
test_embed.html READY (program):4
Browser shows:
test_embed.html
You can also do it the following way:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("#test").hide();
});
$("#show").click(function(){
$("#test").show();
});
});
</script>
</head>
<body>
<h2>This is a test of jQuery!</h2>
<p id="test">This is a hidden paragraph.</p>
<button id="hide">Click me to hide</button>
<button id="show">Click me to show</button>
</body>
the previous answers showed using multiple named functions inside a single .ready block, or a single unnamed function in the .ready block, with another named function outside the .ready block. I found this question while researching if there was a way to have multiple unnamed functions inside the .ready block - I could not get the syntax correct. I finally figured it out, and hoped that by posting my test code I would help others looking for the answer to the same question I had
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.
I am trying to a function to trigger once the body loads. I know that you can do this from the body tag, but I would prefer to do this from JS if this is possible.
For example: document.getElementsByTagName('body').onload = someFunc();
This does not work for me, but I think it shows what I essentially want to do.
EDIT:
I have tried the answers, what seems to be the issue is that it is calling the function before the elements it uses in the body tag are loaded, even if I put the script tags inside the body.
This is what it needs to do:
var buttonElements = document.getElementsByClassName('button');
And if I do:
alert(buttonElements)
It will pop up 0, but when I create a variable in the console, it will successfully populate it with the elements.
What you've got will almost work, but you have to import your JavaScript at the end of the <body> tag, and you have to index the first result:
document.getElementsByTagName('body')[0].onload = someFunc;
Like so:
window.onload = someFunc;
If however, your function accepts arguemnts, you would need anonymous function like this:
window.onload = function(){
someFunc(arg1, arg2);
}
BTW, other than fix that #Pointy mentioned for your code, you can also do:
document.body.onload = someFunc;
Dont use quotes... "someFunc"() won't work if you try to run it anyways.
window.onload = someFunc;
If you use jQuery:
$(document).ready(function () {
callMyFunction();
});
I'd like to change the value of the onclick attribute on an anchor. I want to set it to a new string that contains JavaScript. (That string is provided to the client-side JavaScript code by the server, and it can contains whatever you can put in the onclick attribute in HTML.) Here are a few things I tried:
Using jQuery attr("onclick", js) doesn't work with both Firefox and IE6/7.
Using setAttribute("onclick", js) works with Firefox and IE8, but not IE6/7.
Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return is code passed to eval().
Anyone has a suggestion on to set the onclick attribute to to make this work for Firefox and IE 6/7/8? Also see below the code I used to test this.
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var js = "alert('B'); return false;";
// Set with JQuery: doesn't work
$("a").attr("onclick", js);
// Set with setAttribute(): at least works with Firefox
//document.getElementById("anchor").setAttribute("onclick", js);
});
</script>
</head>
<body>
Click
</body>
</html>
You shouldn't be using onClick any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()
$(document).ready(function(){
var js = "alert('B:' + this.id); return false;";
// create a function from the "js" string
var newclick = new Function(js);
// clears onclick then sets click using jQuery
$("#anchor").attr('onclick', '').click(newclick);
});
That should cancel the onClick function - and keep your "javascript from a string" as well.
The best thing to do would be to remove the onclick="" from the <a> element in the HTML code and switch to using the Unobtrusive method of binding an event to click.
You also said:
Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return in code passed to eval().
No - it won't, but onclick = eval("(function(){"+js+"})"); will wrap the 'js' variable in a function enclosure. onclick = new Function(js); works as well and is a little cleaner to read. (note the capital F) -- see documentation on Function() constructors
BTW, without JQuery this could also be done, but obviously it's pretty ugly as it only considers IE/non-IE:
if(isie)
tmpobject.setAttribute('onclick',(new Function(tmp.nextSibling.getAttributeNode('onclick').value)));
else
$(tmpobject).attr('onclick',tmp.nextSibling.attributes[0].value); //this even supposes index
Anyway, just so that people have an overall idea of what can be done, as I'm sure many have stumbled upon this annoyance.
One gotcha with Jquery is that the click function do not acknowledge the hand coded onclick from the html.
So, you pretty much have to choose. Set up all your handlers in the init function or all of them in html.
The click event in JQuery is the click function $("myelt").click (function ....).
just use jQuery bind method !jquery-selector!.bind('event', !fn!);
See here for more about events in jQuery
If you don't want to actually navigate to a new page you can also have your anchor somewhere on the page like this.
<a id="the_anchor" href="">
And then to assign your string of JavaScript to the the onclick of the anchor, put this somewhere else (i.e. the header, later in the body, whatever):
<script>
var js = "alert('I am your string of JavaScript');"; // js is your string of script
document.getElementById('the_anchor').href = 'javascript:' + js;
</script>
If you have all of this info on the server before sending out the page, then you could also simply place the JavaScript directly in the href attribute of the anchor like so:
Click me
Note that following gnarf's idea you can also do:
var js = "alert('B:' + this.id); return false;";<br/>
var newclick = eval("(function(){"+js+"});");<br/>
$("a").get(0).onclick = newclick;
That will set the onclick without triggering the event (had the same problem here and it took me some time to find out).
Came up with a quick and dirty fix to this. Just used <select onchange='this.options[this.selectedIndex].onclick();> <option onclick='alert("hello world")' ></option> </select>
Hope this helps