I want to append this to my document:
$('#myDiv).append("<div id='myDiv2' onclick="+extElementConfig.onClickDo+">Do</div>");
The snippet above has it's onClick populated by a certain object with properties,
this:
var extElementConfig={onClickDo:sampleFunc()};
Unfortunately declaring a function into the object property also fires it, as was expected.
How can I achieve the above functionality without triggering the
sampleFunc()?
I just need to dynamically populate the onClick event through an object property.
Assuming you have control over the extElementConfig object, remove the parenthesis from sampleFunc
var extElementConfig={extElementPosition :10,extElementId:'mailOrderBtn',onClickDo:sampleFunc};
As Rob. M. pointed out the real problem with your code was the fact you were running the code when it was in the object instead of assigning a reference. And when you tried to assigning the onclick, that had issues too since you are trying to use a function reference when it was a string.
To get your code to run, it would be something like
function sampleFunc () {
alert("clicked");
}
var extElementConfig={onClickDo:"sampleFunc()"};
$('#myDiv').append("<div id='myDiv2' onclick='"+extElementConfig.onClickDo+"()'>Do</div>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myDiv"></div>
To get rid of this, do not use the sting method to build up the element, instead leverage the power of jQuery. Below is an example where I build a div and pass in some arguments to change the element's text and css when clicked.
function sampleFunc(txt, css) {
$(this).text(txt).css(css);
}
var extElementConfig = {
onClickDo: sampleFunc,
onClickArgs : ["Clicked", {"background-color":"green"}]
};
$('<div/>', {
id: 'myDiv2',
text: 'Do!'
}
).on("click",
function() {
extElementConfig.onClickDo.apply(this, extElementConfig.onClickArgs);
}
).appendTo("#myDiv");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="myDiv"></div>
Related
When I initialize bootstrap-wysihtml5 with class name it will only initialize first one and rest of the remain normal text-area
Is there any way to handle it
<script>
$(document).ready(function() {
$('.vid_description').wysihtml5();
});
</script>
I guess, the method wysihtml5() is only called for the first element.
Iterate over all elements and call the initialization method for each element separately:
$('.vid_description').each(function() {
$(this).wysihtml5();
});
sorry for asking that stupid:D However what did i do wrong here?
html:
<div onclick="prompt()" value="test">test</div>
javascript:
function prompt() {
var error = this.value;
alert("sdsd");
}
Thanks!
First off, <div>s don't have a value attribute, so .value won't work. Second, you should not use inline JavaScript.
What you should do is:
<div id="test" value="test">test</div>
Then:
$(function(){
$('#test').click(function(){
// You need to get the attribute from the element
var error = $(this).attr('value');
});
});
If you must use inline events, then you need to pass the element to the prompt() function. The problem is that it doesn't know what this is. This is why you should bind the event as shown above. Anyway, you can also do:
<div onclick="prompt(this)" value="test">test</div>
Then:
function prompt(ele){
// You can't use `.value` because `<div>`s
// don't have a value property
var error = ele.getAttribute('value');
}
P.S. May I also suggest using data-* attributes for this instead of invalid attributes?
<div id="test" data-value="test">test</div>
Then:
$(function(){
$('#test').click(function(){
var error = $(this).data('value');
});
});
The value of this depends on how the function that it appears in was called.
When the browser calls the onclick function from the event trigger, this is the input.
When you call prompt(), because you provided no context and you are no in strict mode, this is the window.
You need to explicitly pass the value.
onclick="prompt.call(this)"
Better yet, don't use intrinsic event attributes in the first place. They mix your HTML and logic and have a whole collection of gotchas to go with them.
Then you have a second problem.
Div elements don't have values. Only inputs and other form controls do. You would need to use .getAttribute("value") instead of .value … but that still leaves your HTML invalid (as well as inappropriate - div elements aren't designed to be interacted with, they give no visual indication that they should be clicked on, and they won't receive the focus should the user not be using a mouse or other pointing device anyway).
You should use a control designed to be interacted with.
Finally, prompt is a built in function, so you should avoid overwriting it and pick a different name instead.
function show_value(event) {
var value = this.value;
document.body.appendChild(document.createTextNode(value));
}
document.querySelector("button").addEventListener("click", show_value);
<button type="button" value="test">test</div>
Div does not have value attribute.
If you need to get the value inside div element you can do it by innerHTML property.
function prompt() {
var error = this.innerHTML; // OR this.getAttribute("value");
}
I am trying to get a class to be added to a div element when clicked. I can not get it to work, I have it set up similar to this:
javascript:
function choose() {
this.addClass("selected");
}
html:
<div class="initialclass" onclick="choose()">CLICK</div>
I have other javascript commands in that function that are working properly I just can't get the class to add.
You have two issues with your current code. First is that this in your JS function refers to the window, not the element that was clicked. Second if it did refer to that element, it would be a DOMElement, not a jQuery object, so it would not have the addClass() method - you need to convert it to a jQuery object. Try this:
<div class="initialclass" onclick="choose(this)">CLICK</div>
function choose(el) {
$(el).addClass("selected");
}
Note however, that it is better practice to hook up your events using JavaScript. As you are using jQuery, you can do this:
<div class="initialclass">CLICK</div>
$(function() {
$('.initialclass').click(function() {
$(this).addClass("selected");
});
});
change your html like this:-
<div class="initialclass" onclick="choose(this)">CLICK</div>
and function:-
function choose(dv) {
$(dv).addClass("selected");
}
Use classList:
classList returns a token list of the class attribute of the element.
el.classList.add("selected");
classList.add:
Adds a class to an element's list of classes. If class already exists in the element's list of classes, it will not add the class again.
CODE
HTML:
<div class="initialclass" onclick="choose(this)">CLICK</div>
Javascript:
function choose(el) {
el.classList.add("selected");
}
DEMO
If you use jquery add this is code in your $(document).ready()
$(".initialclass").click(function(){
$(this).addClass("selected");
});
Basically.... I am using this code
var editorLinks;
editorLinks = $(".admin_editor_link.html");
$.each(editorLinks, function(i, link){
$(link).html($(link).attr("data-loadedtext"));
});
And I am wondering if there is some way to do it without the $.each call... like...
editorLinks.html($(this).attr("data-loadedtext"));
I assumed this would work (or some variation of it that I cant remember) but when I tried it all elements html was set to the data-loadedtext of the first element in the array.
Use a function supplied to html():
editorLinks.html(function(){
return $(this).attr("data-loadedtext");
});
The return value of the function is used as the value for html() for each element.
Using your example HTML in comment:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/taesc0tt/2/
Yes, you can, but you'll need to change the name of your class to admin_editor_link because jQuery selector is trying to find elements with both admin_editor_link and html classes. (Unless, of course, you actually looking for elements with both those classes - your question has no HTML code to verify that - in which case you're fine).
<div data-loadedtext="1" class="admin_editor_link"></div>
<div data-loadedtext="2" class="admin_editor_link"></div>
Just use a function to return the result
var editorLinks = $(".admin_editor_link");
editorLinks.html(function () {
return $(this).attr("data-loadedtext");
});
DEMO
DEMO with both classes
I am overlooking something pretty fundamental here. I want to color a specific element in a group whenever a checkbox is clicked. So I need to make these elements observable.
This is what my html looks like
<p>
<label>
<i>bla2</i>
<input type="checkbox" />
</label>
</p>
<p>
<label>
<i>bla3</i>
<input type="checkbox" />
</label>
</p>
My JS looks like this
$(document).ready(function() {
function handleCheckbox () {
if ( $(this).closest(':checkbox').is(':checked') ) {
$('this').closest('i').css('color','green');
} else {
$('this').closest('i').css('color','red');
}
}
handleCheckbox();
$('label').on('click', handleCheckbox() );
});
.closest() looks at the current element and then up the hierarchy at ancestors, not at neighbors. In your case, this will point to the label object so you can look at children to find the <i> tag and <input> tag. You also have several other coding errors.
Also, your handleCheckbox() function needs the value of this set to a <label> object in order to work properly so you can't just call it direct and expect it to set all the colors appropriately. Instead, you will have to iterate over all the labels in the page and call handleCheckbox() for each one. I've done that in the code below with .each().
Here's a way to fix it:
$(document).ready(function() {
function handleCheckbox() {
// the this pointer here will point to the label object so you need
// can use .find() to find children of the label object
var newColor;
if ($(this).find("input").is(":checked")) {
newColor = "green";
} else {
newColor = "red";
}
$(this).find("i").css("color", newColor);
}
// hook up click handler and initialize the color for all labels
$('label').on('click', handleCheckbox).each(handleCheckbox);
});
See working demo: http://jsfiddle.net/jfriend00/tRQ99/ and also notice that the initial color is set based on the initial checkbox state too.
Your code had these issues:
.closest() goes up to ancestors. It doesn't find neighbors.
When passing a callback function, you don't use the () at the end because that causes it to execute immediately and pass the return value of executing the function. You just want to pass a reference to the function which is done without the parens.
You don't quote this. Treat it like a javascript variable, not a string.
The this pointer will point to the label object in your callback so you need to look at child elements to find the <i> and <input> objects. You can use either .children() or .find() to find them.
You initial call of handleCheckbox() was not working because it works only when this is set to a <label> object (the way it works in the event handler). So, to use the same function for initialization as the event handler, you need to iterate over all the labels and make sure this is set appropriately for that function. A simple way to do that is with .each() as I've shown in my code suggestion.
You're passing a function in rather than using an anonymous function, so remove the ()
$('label').on('click', handleCheckbox);
Else this will execute right away on page load. Also, unquote this:
$(this).closest('i').css('color','green');
Fiddle for what you probably want here:
http://jsfiddle.net/93CeR/2
$(document).ready(function() {
function handleCheckbox () {
if ( $(this).find(':checkbox').is(':checked') ) { // Use .find instead of closest because the element you want is a child
$(this).find('i').css('color','green'); // Remove qoutes from this and use .find for same reason as above
} else {
$(this).find('i').css('color','red'); // Ditto
}
}
$('label').each(function(){
handleCheckbox.apply(this); // We need to call the function initially using 'label' for this.
});
$('label').on('click', handleCheckbox ); // You want a reference to handleCheckbox not to invoke it so remove the parenthesis
});