How to change the background of a specific div when clicked - javascript

Note: I don't know jQuery so please don't give me an answer how how to do it using jQuery.
I have multiple divs. I want to know how I could access it and change its specific color when clicked using JavaScript.
I am not looking for a solution like document.getElementsByTagName("div")[0] because it requires inputting a seperate number for each div.
I was hoping there was a simple solution somewhat like this.
<div onClick="change();"><h1>Hi</h1><div>
<div onClick="change();"><h1>Hi</h1><div>
<div onClick="change();"><h1>Hi</h1><div>
<script>
function change(){
this.style.backgroundColor = "red";
}
</script>

Since you don't want to learn jQuery (or presumably, non-inline events), consider:
<div onclick="change(this)"><h1>Hi Dave!</h1></div> <!-- use closing tags -->
<div onclick="change(this)"><h1>Hi Thomas!</h1></div>
function change(elm) {
elm.style.backgroundColor = 'red'
}
Note that the context (this) of the inline event handler code (as specified in the attribute) is the element which was the target of the event - for this case it will be the specific DIV element that was clicked. We then simply pass the element into the callback function so we can use it generically.
Also, in the initial markup, the div elements were not closed and led to nesting. With the corrections, the above approach works to complete the task. (The fiddle code assigns to window.change directly, but it's otherwise the same concept.)
Of course, learning jQuery (or a different) high-level framework will probably pay off quite quickly. Using inline event-handlers is .. very "old school".

This would be more easy.
<div onclick="changeColor(this)">Some text!</div>
<p>A paragraph, that will have no change by click</p>
For JavaScript write this:
function changeColor(div) {
div.style.backgroundColor = #hexvalue
}
This will change the background color of the div and not the <p>. You can set any css value for any element by using this jQuery code.
However, for me the jQuery was pretty easy! :) But as you wish.

Related

Assigning JQuery On Click Function in For Loop

I have a function that dynamically creates div elements based upon whatever input is given, and lets them choose certain items by clicking on each div. I have it so that if the div is clicked, a function (named checkToggle) is called that makes it looks like it is selected and adjusts some related variables. There is a checkbox in the div element that is toggled by this function (hence its name). Long story short, I had to jump through some hoops to get it to work, most of which I don't even remember. Please don't ask me about that.
The point of this question is this. I initially used the following JavaScript code to run the function when the checkbox was clicked. It was assigned by the main function, which created these div elements using a for loop.
document.getElementById(`${itemID}-checkbox`).onclick = function() {
checkToggle(`${itemID}-checkbox`);
};
This works, but I wanted to try to convert all of my onClick functions to JQuery. Here is the JQuery alternative I created.
$(`${itemID}-checkbox`).on(`click`, function() {
checkToggle(`${itemID}-checkbox`);
});
While the code itself seems to be fine, it does not work. It seems as if JQuery functions cannot be created like this in a for loop or something. It is applied after the element is created and put in its place, so I don't think it has anything to do with the element not being ready. I am also having the same issue with 2 other similar cases. Any idea as of why this isn't working?
Let me know if more information is needed and if so, what kind of information is needed.
You need to update the selector to Target HTML id using the # character. Simply prepend the character to the query:
$(`#${itemID}-checkbox`).on(`click`, function() { checkToggle(`${itemID}-checkbox`); });
It would also apply to DOM methods querySelector or querySelectorAll as well.
Hopefully that helps!

How to prevent javascript/jquery execution on specific HTML element?

What is the possibility of the $subject?
Just imagine I have a foo html element
e.g.
<div data-toggle="loader">...</div>
and have a jquery function binded to it by default,
e.g.
$(document).ready(function(){
$('[data-toggle=loader]').loader();
});
So this will change the DOM element to something like,
e.g.
<div data-toggle="loader" class="active" style="height:800px">...</div>
So what I want to do is prevent applying the changes to the foo element, if it has a class name .example. So the catch is, I cannot touch the default execution code. But I can write another function to handle it. That is the problem I'm facing right now. Any possibility of achieving this?
Easiest would be to either change the DOM structure, i.e. so the JS no longer finds the element, or overwrite the jQuery plugin with something innocuous. Do this in a script after the plugin script itself has loaded.
jQuery.fn.loader = jQuery.noop; //$.noop is an empty, pointless function
[EDIT]
In light of the OP's comment, the best bet may be to store a clone of the element then replace the original element with it after the plugin has fired.
var
el = $('.some-element'),
clone = el.clone(1, 1);
//some time passes... plugin is called... does nothing to element
el.replaceWith(clone);

Getting the current div id in content-editable div(specific)

I am recently working on one of my projects and currently i am stuck in some problem. Well, i have made a content editable div where the user can type its input. This content_editable div contains several div's in which user has to type. I tried document.activeElement but it gives me the content_editable div not the specific div and that the one with id second_div
I want to know how to find that specific div in content_editable div where user is type.For example:-
<div contenteditable="true" id="content_editable_div">
<div id="first_div">
I am the first div
</div>
<div id="second_div">
I am the second div and i want to know if the focus is on me
</div>
</div>
My Javascript:
window.onload = function () {
getDivwhohasfocusincontentedtiablediv(); // Something like that
};
I can use jquery but only at the last choice. I want to use only javascript for this purpose.Please help me to solve this, i didn't find solution for this all the net ( it could be that i haven't searched carefully). Thanks in advance
One possible solution is to attach an Event Listener on each inner div to listen for "focus" event. However I found out that not all elements emit "focus" events.
JQuery docs says:
The focus event is sent to an element when it gains focus. This event
is implicitly applicable to a limited set of elements, such as form
elements (input, select, etc.) and links (a href). In recent
browser versions, the event can be extended to include all element
types by explicitly setting the element's tabindex property. An
element can gain focus via keyboard commands, such as the Tab key, or
by mouse clicks on the element.
Adding tabindex attribute to each inner div will make it possible to listen to focus events.
Example at JSFiddle. Note: I wrote the code in JQuery but it can easily be written in JS.
You can find focus element in js using this,
var focused = document.activeElement;
What about this ,
<div contenteditable="true" id="content_editable_div">
<div id="first_div">
First Div
</div>
<div id="second_div">
Second Div
</div>
</div>
$(document).ready(function () {
function onMouseUp(e) {
console.log(this.id);
}
document.getElementById("first_div").addEventListener("mouseup", onMouseUp, false);
document.getElementById("second_div").addEventListener("mouseup", onMouseUp, false);
});
Demo Here JS FIDDLE
to get specific div
in Javascript you can use
document.getElementById("second_div")
or using Jquery
$("#second_div")
make sure your id was unique. This is the fastest way to find obj in any browser.
now for getting getting the active div. why not put specific event whenever the div was clicked or edited. like:
$("#second_div").click (function (){
//raise flag or something
currentDiv = "second_div";
})
function getCurrentDiv()
{
//do something in currentDiv
}
or try also explore other event such as, on mouse over, on mouse leave, etc.
i hope that might help. other wise, please elaborate your question if I missed something.

Jquery remove function follow up

I submitted this question last week:
chrome not working with jquery remove
and was able to resolve it (stupidity on my part really), however my example was very simple. Currently I'm trying to use .remove to eliminate a complete div from a page before sending an array of inputs to an ajax function. However, I am not able to get .remove to work at all.
Here's my latest try:
http://jsfiddle.net/CJ2r9/2/
I get function not defined on the jsfiddle on multiple browsers. On my application I get absolutely no errors, but nothing works either.
I'm relatively new to javascript scopes, so if the problem is scope-wise then please let me know how I'm screwing up.
I have also tried using the .on jquery function, but it's a bit more confusing considering my div ids are dynamically loaded from the server (jstl, spring MVC, etc). If that's a solution please let me know how I can get on the right track.
Thank you!
The two problems in your jsFiddle are:
Scope: removeElem is not in global scope, since you left the default configuration option to execute the code on DOM ready. You can change it to "no wrap" to make the funciton global.
The elements you want to remove don't exist. The div elements have IDs like "removeXXXp" and in your event handlers you pass "removeXXXs".
Here is an other, simpler solution (in my opinion) for element removal. Given your markup:
<div class="scheduleSet" id="remove315p">
<!-- ... -->
Remove
</div>
You can use .on like so:
$('.schduleSet a.optionHide').on('click', function() {
// traverses up the DOM tree and finds the enclosing .schduleSet element
$(this).closest('.scheduleSet').remove();
});
You don't even need IDs at all.
I made a simple fiddle, the inline onclick doesn't see the function defined in javascript so I get a ReferenceError: myRemove is not defined.
By adding the listener in js, .remove() works fine.
Sorry I don't know what causes the difference in behavior though.
Test it out: http://jsfiddle.net/xTv5M/1/
// HTML5
<div id="removeme">foo bar</div>
<button onclick="myRemove('removeme')">Go</button><br>
<div id="removeMe2">foo bar</div>
<button id="go2">Go Again</button>
// js
function myRemove(name){
$('#'+name).remove()
};
$('#go2').click(function(){ myRemove('removeMe2') });
I see that you are already using jquery. Why dont you do it this way:
<div id="foo">This needs to be removed</div>
Remove
function removeElem(element){
$('#'+element).remove();
}
$(function(){
$("#remove").click(function(){
removeElem($(this).data('remove'));
});
})
Fiddle here: http://jsfiddle.net/vLgpk/
They way this works is, using data-remove (can be anything like data-xyz btw), binds the remove link with the div. You can then read this binding later when remove is clicked.
If you are new to jQuery, and wondering what data-remove is, its just custom attribute that you can add to you code which can be later retrieved using the data() call on the element. Many great frameworks like Bootstrap use this approach.
Advantage of using this approach in my opinion is you can have the remove links anywhere in your UI and they don't need to be related structurally to your divs by siting inside them.

How can I remove an element in Javascript without jQuery

Im trying to remove a Div from the DOM via an <a> tag nested within it.
I guess what I am looking for is the pure Javascript version of jQuery's
$('div').remove()
Here's the html set up
<div> Click me to remove the parent div</div>
Thanks ahead of time. :D
You could define this function
function remove(element) {
element.parentNode.removeChild(element);
}
and use it as
<div>
...
</div>
Reference: Node.parentNode, Node.removeChild
Further notes:
You better use a <button> instead of a link (<a>) for this kind of behaviour. A link has a distinct semantic meaning, it has to link somewhere. You can use CSS to style the button accordingly.
Event handlers are better added via JavaScript itself and not as an HTML attribute.

Categories