<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<style>
.bold {
font-weight: bold;
}
.blue {
color: blue;
}
</style>
Toggle class
<script type="text/javascript">
function ToggleClass()
{
if($(this).hasClass("bold"))
{
$(this).removeClass("bold");
}
else
{
$(this).addClass("bold");
}
}
</script>
Question:
I made one function: ToggleClass, but it does not work, what is the problem?
The reason why it doesn't work is two-fold:
No explicit binding
You're using inlined code:
Toggle class
Even though the code inside the onclick parameter is run in the right context, the function call gets invoked in the context of window, i.e. inside ToggleClass(), by default, this refers to window; it's as if ToggleClass.call(window) was written. You can bind the function to another object if you wish:
Toggle class
Using .call() you bind the current element to the function and it will work as expected.
Not enough jQuery
You're not doing things in the jQuery way.
Toggle class
...
<script>
jQuery(function($) {
$('.toggle-bold').on('click', function() {
$(this).toggleClass('bold');
return false; // prevent navigation to #
});
});
</script>
I've removed the href="javascript:void(0);" and the inlined code. Instead, I've added a class to target the anchor; if the link only occurs once inside the document, you may want to consider a unique identifier. The click handler is attached once the document is ready.
To prevent the browser from adding that pesky # at the end, I'm returning false from the click handler to stop event propagation.
Lastly. instead of hasClass(), addClass() and removeClass() I'm using toggleClass().
you need to send reference to the calling function
... onclick="ToggleClass(this);"...
<script type="text/javascript">
function ToggleClass(obj)
{
if($(obj).hasClass("bold"))
$(obj).removeClass("bold");
else
$(obj).addClass("bold");
}
however i always prefer using click function rather than inline javascript
Toggle class
<script>
$('#ToggleClass').click(function(){
if($(this).hasClass("bold"))
$(this).removeClass("bold");
else
$(this).addClass("bold");
});
</script>
Using jQuery the implementation should be as simple as using the .toggleClass() utility method:
Toggle class
<script type="text/javascript">
jQuery(function($)
{
$('#toggleme').click(function()
{
$(this).toggleClass('bold');
});
});
</script>
You're using an inline onclick handler. Your HTML:
onclick="ToggleClass();"
Is interpreted similarly to:
element.onclick = function(event) {
//`this` is available inside the onclick method
ToggleClass(); //but it is not passed to called functions automatically
}
You're just calling a function, hence the this reference is not set inside this ToggleClass execution. By "not set", I mean in the ES aspect: entering function code with an undefined this means that the this reference will point to the window object, or undefined when in strict mode.
One way to set the this reference for a function execution context is using Function.call or Function.apply:
onclick="ToggleClass.call(this, event);"
Read more about the this keyword here.
*event is not necessary with your code, but event handlers usually expect to receive an event object hence I'm passing it anyway.
However, you're already using jQuery, which sets the this reference inside event handlers and wraps the event object to make its methods cross-browser. Hence you can just add a JS hook to your element and attach listeners through jQuery:
Toggle class
<script>
$('.js-toggleClass').click(function(e) {
e.preventDefault();
$(this).toggleClass('bold');
});
</script>
Demo
I've replaced your href="javascript:void(0)" with the jQuery Event object's preventDefault() method as JavaScript does not belong inside href attributes, and used the jQuery .toggleClass() method to simplify your logic as well.
The pros of this is the separation between structure (HTML) and behavior (JS), thus keeping your code much more organized and modularized.
You are calling function ToggleClass(), but yoy are not passing parameter when calling ToggleClass() function , Pass Reference when calling ToggleClass(), otherwise buildin function exists in JQuery.
Send current object in toggleClass() function like this :
ToggleClass(this)
Toggle class
<script type="text/javascript">
function ToggleClass(abc)
{
if($(abc).hasClass("bold"))
$(abc).removeClass("bold");
else
$(abc).addClass("bold");
}
</script>
i hope it will help you
Related
I am a beginner & self interested web coder.
I have been testing, asking, retesting, trying, reading up on different functionality solutions in javaScript to an online form which will consist of a multitude of <textarea>'s once I am done.
I am fairly ok, with the current state of functions, which are based upon several js events. Example code would be (written funny so it is easier to read in the forum, actual code is one line obviously):
<textarea
data-id="0"
class="classOne classTwo"
id="dataInput_0"
name="xInput_row_1"
onFocus="functionOne();"
onBlur="functionTwo();"
onKeyUp="functionThree();">
</textarea>
I built and tested all the functions to work specifically on the id="dataInput_0" using getElementById. Example:
var d = document.getElementById("dataInput_0");
So my question is how to I make the functions trigger for other "dataInput" id's?
In other words:
var d = document.getElementById('whichever dataInput that is active/focused');
Thanks!
The simplest way to work with your current code would be to do this:
onFocus="functionOne(this);"
...and then define your function:
function functionOne(el) {
// el is the element in question, used e.g.:
alert(el.name);
}
Within the onFocus=... the browser sets this to the element in question, so you can then pass it as a parameter to your function. Your function then just uses it directly rather than having to go via getElementById().
But since you mentioned jQuery, you could remove the inline onFocus and other onXYZ handlers from your html and just do it all in your JS as follows:
$("textarea").focus(function() {
// here this is the element in question, e.g.:
alert(this.value);
});
That defines a focus handler for all textareas on the page - to narrow it down to just textareas with class "classOne" do $("textarea.classOne"). Within the function this refers to the focused element. You could use the .blur() and keyup() methods to assign handlers for the other events shown in your code.
My suggestion is to use attribute selector $('input[id^="dataInput_"]') for this and use the jQuery's .on() handler this way:
$('input[id^="dataInput_"]').on({
focus: function{
functionOne($(this));
},
blur: function(){
functionTwo($(this));
},
keyup: function(){
functionThree($(this));
}
});
and the functions:
functionOne(obj){
console.log(obj.val());
}
functionTwo(obj){
console.log(obj.val());
}
functionThree(obj){
console.log(obj.val());
}
I'm not really a developper. I prefer to design my websites ... So, for my actual project, i must developping some "basic" scripts.
I've met a problem with this:
<script type="text/javascript">
$("button").click(function toggleDiv(divId) {
$("#"+divId).toggle();
});
;
</script>
Into Head-/Head
LINK
<div> id="myContent">Lorem Ipsum</div>
It works for IE8. (Miracle). But not the others browsers...
The idea is that when u click on "LINK" a windows appears and when you click again, the window close.
Any idea ?
Thanks for u time !
One of the problems is you're mixing two different styles of binding event handlers: one of them is good (the jQuery method), the other is bad (the javascript: protocol in your href attribute) - the two don't work together in any way. Another problem is that your selector is completely incorrect (it's looking for a button) for the HTML you've provided (you never create a button).
I'd suggest using a HTML5 data-* attribute to specify the id for the <div> on your <a> element:
LINK
<div id="mycontent">Lorem ipsum</div>
Then use the following jQuery code:
$('a').click(function(e) {
e.preventDefault(); // e refers to the event (the click),
// calling preventDefault() will stop you following the link
var divId = $(this).data('divid');
$('#' + divId).toggle();
});
Note that I've used this in the above code; what this refers to depends on the context in which you use it, but in the context of a jQuery event handler callback function, it will always refer to the element that triggered the event (in this case, your <a> element).
If you extract toggleDiv from the handler, it ought to work. You will probably also need to return false to keep the href from trying to go anywhere.
<script type="text/javascript">
function toggleDiv(divId) {
$("#"+divId).toggle();
return false;
}
</script>
Once again I've inherited someone else's system which is a bit of a mess. I'm currently working with an old ASP.NET (VB) webforms app that spits JavaScript onto the client via the server - not nice! I'm also limited on what I can edit in regards to the application.
I have a scenario where I have a function that does a simple exercise but would also need to know what item was clicked to executed the function, as the function can be executed from a number of places within the system...
Say I had a function like so...
function updateMyDiv() {
$('#div1').hide();
$('#div2').hide();
$('#div13').show();
}
how could I get the ID (for example) of the HTML element that was clicked to execute this?
Something like:
function updateMyDiv() {
alert(htmlelement.id) // need to raise the ID of what was clicked,
$('#div1').hide();
$('#div2').hide();
$('#div13').show();
}
I can expand on this if neccessary, do I need to pass this as an arguement?
The this keyword references the element that fired the event. Either:
<element onClick="doSomething(this);">
or
element.onclick = function() {
alert(this.id);
}
Bind your click events with jQuery and then reference $(this)
$('.myDivClass').live('click', function () {
updateMyDiv(this);
});
var updateMyDiv = function (that) {
alert(that.id);
// save the world
};
You don't need to pass "this", it is assigned automatically. You can do something like this:
$('div').click(function(){
alert($(this).attr('id'));
})
Attach the function as the elements event handler is one way,
$(htmlelement).click(updateMyDiv);
If you are working with an already generated event, you can call getElementByPoint and pass in the events x,y coords to get the element the mouse was hovering over.
$('.something').click(function(){
alert($(this).attr('id'));
});
You would need to pass it the event.target variable.
$("element").click(function(event) {
updateMyDiv($(event.target));
});
function updateMyDiv(target) {
alert(target.prop("id"));
}
Where is your .click event handler? Wherever it is, the variable this inside of it will be the element clicked upon.
If you have an onclick attribute firing your function, change it to
<tag attribute="value" onclick="updateMyDiv(this)">
and change the JavaScript to
function updateMyDiv(obj) {
alert(obj.getAttribute('id')) // need to raise the ID of what was clicked,
$('#div1').hide();
$('#div2').hide();
$('#div13').show();
}
use the .attr('id') method and specify the id which will return what you need.
I have a simple javascript code which replaces the page content....by contents of another file(test2.html)
Code:
$(document).ready(function(){
$("[href='#']").click(function() {
function getcontent(url, id) {
$("#id").load("url");
}
});
});
Now am using
<div id = "content">
<p> REPLACE </p>
</div>
click here
So now on clicking click here REPLACE should be replaced by content of test2.html...but its not happening...
I have included the required jquery.js file in my script..
No, this won't work. getcontent is a function defined in a particular scope -- that of the click handler callback function. It is not accessible in the global scope -- the scope that the onClick method receives.
You should use a genuine click handler, perhaps setting data using data attributes:
$('[href="#"]').click(function() {
$('#' + $(this).data('id')).load($(this).data('url'));
});
Using the following HTML:
click here
You have a weird setup. The function getcontent is not defined in global scope, it cannot be found by the onclick event handler in the HTML. There are other issues as well.
I suggest something like:
click here
and
$(function(){
$("a[href^='#']").click(function(){
$(this.href).load(this.rel);
});
});
$('#' + id).load(url);
In your current method above, you are passing string literals, not the variables themselves.
You seem to be misunderstanding what certain parts of your code are doing. Also, I'd recommend giving your href a real id to make things easier. You don't need to use the jQuery 'click' method and ALSO assign an onclick handler inline in the HTML.
Try this instead:
<div id = "content">
<p> REPLACE </p>
</div>
<a id="clickThis" href="#">click here</a>
$(document).ready(function() {
$('#clickThis').click(function() {
$('#content').load('test2.html');
});
});
Your code with some comments:
$(document).ready(function(){
// this will assign a click handler, you don't need an 'onclick'
// attribute on the anchor tag also
$("[href='#']").click(function() {
// but what does your click handler do?
// It defines a function that is never called.
function getcontent(url, id) {
$("#id").load("url");
}
});
});
How do you change the JavaScript that will execute when a form button is clicked?
I've tried changing its onClicked and its onclicked child attributes like so:
$('mybutton').onClick = 'doSomething';
and
$('mybutton').attributes["onclick"] = 'doSomething()';
Neither seem to work. My other options are:
To have two buttons and hide one and show the other.
To have it directed to a function that evals a string and change the string to the function I want to execute.
Neither seem very elegant.
I'm using Prototype as a js library so it that has any useful tools I can use them.
If the original onclick event was set through HTML attributes, you can use the following to overwrite it:
$("#myButtonId").setAttribute("onclick", "myFunction();");
For Prototype, I believe that it would be something like this:
$("mybutton").observe('click', function() {
// do something here
});
EDIT: Or, as it says in the documentation, you could simply specify the function you want to call on click:
$('mybutton').observe('click', respondToClick);
function respondToClick(event) {
// do something here
}
But this is all, again, Prototype-specific.
Using the Prototype framework you can do:
Event.observe("mybutton", "click", clickHandler);
or:
Event.observe("mybutton", "click", function() {
alert("Button clicked!");
});
or:
$("mybutton").observe("click", clickHandler);
or:
$("mybutton").observe("click", function() {
alert("Button clicked!");
});
See the Event class documentation
The general way to set an onclick handler in javascript is to set onclick to a function, by passing it the name of a function directly, not in a string. So if myButton is set to a DOM Element, you would write:
myButton.onclick = doSomething;
So when you click the 'mybutton' button, the doSomething function will be called as doSomething(). For anonymous functions, you can write:
myButton.onclick = function() {
alert("myButton was clicked!");
};
In JQuery it's
$("#myButtonId").click(myFunction);
function myFunction(){
alert("Clicked");
}
Or if you want to put the function inline:
$("#myButtonId").click(function(){
alert("Clicked");
});
If you are using JQuery firstly make sure you use the relevant selector prefix (IE: If your using the Id of the element put a # in front of it). Secondly it's the click method to assign a callback to the click event.
Last I used Prototype, it was something like this:
Event.observe('mybutton', 'click', doSomething);
By the way, your examples might've even worked if you didn't quote the function names.
EDIT: Yes, Element.observe(element, eventName, handler) and someElement.observe(eventName, handler) also work. And don't quote the handler name - you want to pass the function not a string!
I found a solution for your issue with prototype under firefox:
$("#myButtonId").writeAttribute('onclick', ''); // first remove the attribute
$("#myButtonId").observe('click', function () { ... }); // then add the event