change div class,id,.. in every click - javascript

I trying to run code to change div id,class,... in every click but I don't
know how this my js code :
<div class="up_vote_bt upvote_hide" title="Delete up vote" onclick="upvoteHide()" id="hideupvote"></div>
<script>
$(document).ready(function() {
$("#upvote").click(function() {
document.getElementById("upvote").setAttribute("class","up_vote_bt upvote_hide");
document.getElementById("upvote").setAttribute("title","delete up vote");
document.getElementById("upvote").setAttribute("onclick","hideupvote()");
document.getElementById("upvote").setAttribute("id","hideupvote");
});
});
</script>
<script>
$(document).ready(function() {
$("#hideupvote").click(function() {
document.getElementById("hideupvote").setAttribute("class","up_vote_bt");
document.getElementById("hideupvote").setAttribute("title","up vote");
document.getElementById("hideupvote").setAttribute("onclick","upvote()");
document.getElementById("hideupvote").setAttribute("id","upvote");
});
});
</script>

if you're using jQuery why not do this?
$(document).ready(function(){
$('#upvote').click(function(){
//$(this) for just this element
if($(this).hasClass('upvote_hide')){
$(this).attr('title','Up vote');
upvote();
}else{
$(this).attr('title','Delete up vote');
hideupvote();
}
$(this).toggleClass('upvote_hide')
});
});
toggleClass() will either add or remove upvote_hide if it doesn't exist or exists.
attr() will alter the attribute much like setAttribute()
For my example there is no need to alter the eventHandlers or in your case setting the attribute onClick to the function. I'ts all done in the jQuery event hander function. So your functions that you're passing to the onclick attribute are called within the function.

When you attach an event handler via jQuery using the
$("#upvote").click(function() { ... });
mechanism, jQuery will directly attach the handler to the elements in the query result set. This means that the handler will be there, whatever the ID changes to in the future.
What you can do is to attach a delegated handler to the document like this.
$(document).on("click", "#upvote", function() { ... });
$(document).on("click", "#hideupvote", function() { ... });
See this article for a deeper explanation
Also, setting the onclick attribute is meaningless in this case and you should remove those lines.
However, changin IDs of elements is not a good practice. An ID should mean a unique identifier for a DOM node, which is not expected to change. I would rather toggle classes here.

Related

How to convert jQuery to JavaScript name attribute

I'm trying to find a way to create 'on click' events for dynamically generated buttons in JS. I know that in jQuery it can be done like this:
$(document).on('click', 'name=[buttonName]', function() {});
I know the e.target method in JS, but I'm wanting to find a way to do it with a name attribute instead.
Thanks
Firstly that line of jQuery isn't quite right as the square brackets are in the wrong place:
$(document).on('click', '[name="buttonName"]', func);
To achieve the same in plain JS you would need to attach a click event handler to a static parent element, then check the name property of the clicked element:
document.addEventListener('click', function(e) {
if (e.target.name == 'buttonName') {
// do something...
}
});
document.addEventListener('click', function(e) {
if (e.target.name == 'buttonName') {
alert('Hello!');
}
});
<button>I do nothing!</button>
<button name="buttonName">I say hello!</button>
You can use querySelector in a similar way than you would in jQuery, and attach the event listener whenever a new element is added to the DOM.
document.querySelector("button[name='buttonName']").addEventListener("click", function(){
alert("Hello, World");
});
<button name="buttonName">Click me</button>
The difference to the original jQuery code is that in that example it listens to events on the document whereas this does not.
You can use getElementByName to add click event to your button which is dynamically render
document.getElementByName("ButtonName").addEventListener("click", function(e) {
});

Trying to write a function from inline javascript

I've got some code from a developer that left our company. He wrote an inline function looking like this:
<button class="xxx" id="MyID" type="button" onclick="javascript: $('#openThis').slideToggle('slow');">btnText</button>
I've tried to remove this and put it in another function to write a callback so I can scroll to the toggled area when it's visible.
$("#MyID").click(function () {
$("#openThis").slideToggle("slow");
});
But I can't seem to get it to work. What am I doing wrong?
are you adding the listener before or after the object is created on the DOM?
because if you are trying to bind that onclick function without waiting the document to be ready theres no object to create the listener.
something like this could work:
$(document).on('ready', function() {
$("#MyID").click(function () {
$("#openThis").slideToggle("slow");
});
});
If you button is added dynamically then use on instead of click
Attach an event handler function for one or more events to the
selected elements.
Event handlers are bound only to the currently selected elements; they
must exist at the time your code makes the call to .on()
//Instead of document you can use a container id
$(document).on('click',"#MyID",function () {
$("#openThis").slideToggle("slow");
});
What this approach does is it adds event to a currently selected element which is document here and it will delegate the event to your selector which is #MyID in this case.
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time.
$(document).on('click', '#myBtn', function(){
$('#foo').slideToggle('slow');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="foo">content</div>
<button id="myBtn">Click me</button>
You want to scroll to the area so remove the JavaScript from the button
You need to do something like this
$("#MyID").click(function() {
$('html, body').animate({
scrollTop: $("#openThis").offset().top
}, 2000);
$("#openThis").slideToggle("slow");
});
You should delete the onclick="" attributes in the button tag and in your javascript :
$("#MyID").click(function (e) {
e.preventDefault();
$("#openThis").slideToggle("slow");
});
Use the prevent default.
Hope that help

.click() not working on a specific index

I'm creating a dynamic menu where I can add and remove a new form.
<input type="button" value="generate form" id="test"/>
<div id="form1"></div>
<script>
$(document).ready(function() {
$("#test").click(function() {
$("#form1").append("<select id='score-attempt'><option value='penalty'>penalty</option></select><input type='button' value='remove' id='remove'/><br>");
});
$("#form1 #remove").click(function() {
alert($(this).index());
});
});
The problem is that clicking on remove never triggers the alert box.
Thanks
The problem is that the element is added later and doesn't exist when the dom is loaded. Therefore the click event has to be delegated from an already existing element, e.g. like this:
$(document).on("click", "#remove", function(){
alert($(this).index() );
});
Instead of $(document) every other static parent element can be used for event delegation, just as example.
Update for the comments: as mentioned, $(document) only as example. I'd also prefer to use $("#form1") here like mithunsatheesh suggested.
And for reference: https://api.jquery.com/on/#on-events-selector-data-handler, section "Direct and delegated events":
"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."
Update for the correct index: you'll get the correct index using e.g.
$("#form1").on("click", ".remove", function(){
alert($(".remove").index($(this)));
});
with the adjustment to use remove as class instead of id for the remove-button. IDs have to be unique, so classes are a better solution. index() starts counting with 0, so you'll get 0 for the first one.
As working example: Fiddle
You need to add an event handler on your #form1 input with #remove.
Look here, here and here.
Here is the working jsfiddle for you.

Add click event on div tag using JavaScript

I have a div tag in my form without id property. I need to set an on-click event on this div tag.
My HTML code:
<div class="drill_cursor" >
....
</div>
I don't want to add an id property to my div tag.
How can I add an on-click event on this tag using JavaScript?
Pure JavaScript
document.getElementsByClassName('drill_cursor')[0]
.addEventListener('click', function (event) {
// do something
});
jQuery
$(".drill_cursor").click(function(){
//do something
});
Try this:
var div = document.getElementsByClassName('drill_cursor')[0];
div.addEventListener('click', function (event) {
alert('Hi!');
});
Just add the onclick-attribute:
<div class="drill_cursor" onclick='alert("youClickedMe!");'>
....
</div>
It's javascript, but it's automatically bound using an html-attribute instead of manually binding it within <script> tags - maybe it does what you want.
While it might be good enough for very small projects or test pages, you should definitly consider using addEventListener (as pointed out by other answers), if you expect the code to grow and stay maintainable.
Recommend you to use Id, as Id is associated to only one element while class name may link to more than one element causing confusion to add event to element.
try if you really want to use class:
document.getElementsByClassName('drill_cursor')[0].onclick = function(){alert('1');};
or you may assign function in html itself:
<div class="drill_cursor" onclick='alert("1");'>
</div>
the document class selector:
document.getElementsByClassName('drill_cursor')[0].addEventListener('click',function(){},false)
also the document query selector https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector
document.querySelector(".drill_cursor").addEventListener('click',function(){},false)
Separate function to make adding event handlers much easier.
function addListener(event, obj, fn) {
if (obj.addEventListener) {
obj.addEventListener(event, fn, false); // modern browsers
} else {
obj.attachEvent("on"+event, fn); // older versions of IE
}
}
element = document.getElementsByClassName('drill_cursor')[0];
addListener('click', element, function () {
// Do stuff
});

$('body').on('click', '.anything', function(){})

$('body').on('click', '.anything', function() {
//code
});
doesn't work for anything right now and I can't figure out why. I'm able to anchor to anything else, say I just toss a #wrap div right inside the body. Then I'm able to do
$('#wrap').on('click', '.anything', function() {
//code
});
for any element I want.
Any idea what I could have done to disable this ability on the body element?
Thanks!
You should use $(document). It is a function trigger for any click event in the document. Then inside you can use the jquery on("click","body *",somefunction), where the second argument specifies which specific element to target. In this case every element inside the body.
$(document).on('click','body *',function(){
// $(this) = your current element that clicked.
// additional code
});
You can try this:
You must follow the following format
$('element,id,class').on('click', function(){....});
*JQuery code*
$('body').addClass('.anything').on('click', function(){
//do some code here i.e
alert("ok");
});
If you want to capture click on everything then do
$("*").click(function(){
//code here
}
I use this for selector: http://api.jquery.com/all-selector/
This is used for handling clicks: http://api.jquery.com/click/
And then use http://api.jquery.com/event.preventDefault/
To stop normal clicking actions.

Categories

Resources