Include HTML DOM into addEventListener() - javascript

I am trying to create a simple drag and resize system and I am having problems with adding event listeners to my dividers. Instead of adding the horrendous amount of event listeners to my HTML to every single divider with the class "draggablePanel":
<div id="content">
<div class="draggablePanel" onmousedown='dragShift.dragStart(this,this.parentElement,event)' onmouseup='dragShift.dragEnd(this.parentElement); dragShift.dragHover(this,this.parentElement,event)' onmouseenter= 'dragShift.dragHover(this,this.parentElement,event)' onmouseleave='dragShift.dragEnd(this.parentElement),dragShift.dragLeave(this.parentElement)';>
Content
</div>
</div>
I'm trying to use addEventListeners() for the job:
function addDragPanels(panelArrayName) { //Add the mouse event listeners to draggable panels
if (document.getElementsByClassName) { //Access every divider with the "draggablePanel" class
var divEle;
var draggablePanels = document.getElementsByClassName(panelArrayName);
for(var ctr=0;ctr<draggablePanels.length;ctr++){
divEle = draggablePanels[ctr];
divEle.addEventListener('mousedown', dragShift.dragStart(this,this.parentElement,event),false); //How do i go about editing this?
divEle.addEventListener('mouseup', dragShift.dragEnd( .... etc
}
}
}
if (document.readyState === "complete") {
addDragPanels("draggablePanel");
}
Basically, I am using three arguments: this,this.parentElement,event. How do I correctly pass these arguments using Javascript when I am using addEventListener()? I need the "event" argument to track mouse position in my dragging Javascript functions.
Thanks in advance for any help rendered. Sorry if this question is stupid has been asked before but I just couldn't find the solution anywhere (or maybe I don't know where and what to look).

Where you get this 'dragShift' element? Please refer me to the source.
Some browsers don't support 'addEventListener()'.
Hence, you can use:
divEle.onmousedown = function(){dragShift.dragstart(this,this.parentElement,event);};
or make an anonymous function then put it inside:
divEle.addEventListener('mouseup',function(){dragShift.dragStart(this,this.parentElement,event);},false);
Please let me know if any of it works!

Related

Add Attribute to existing div Tag via Javascript

I'm working on a WordPress website.
All I want to do, add the attribute onclick="off() to an existing div class via javascript (so that the div always has this attribute when the site is loaded). the content plugin I use creates div's automatically, so instead of editing the source code each time, this seems like a nice and fast solution.
right now I'm trying this, but it doesn't work (i know almost nothing about js):
function myfunction() {
document.getElementById("#content_al").setAttribute("onclick","off")
}
I read many threads but didn't get it to work, can anyone help me :)?
off in setAttribute should be off()
Do not pass # in document.getElementById("#content_al"), instead pass plain id i.e. content_al
function myfunction() {
document.getElementById("content_al").setAttribute("onclick", "off()")
}
function off() {
console.log("clicked on off!");
}
myfunction();
<div id="content_al"> Some Content </div>
try jquery. it's easy
jQuery("#content_al").click(function(){
//do action
});
this code defines a click event for your element and you can write your action to run after event fired.
For adding an event handler you should use addEventListener. Below is how you can do it with vanilla javascript.
function myfunction() {
document.getElementById("content_al").addEventListener("click",off)
}
where off is a function
Below is a working snippet. Hope this helps :)
function toggleDisplay() {
let display = document.getElementById("content_al").style.display;
document.getElementById("content_al").style.display = display == "none" ? "block" : "none";
}
function myfunction() {
document.getElementById("hide").addEventListener("click", toggleDisplay);
}
myfunction();
<div id="content_al"> Some Content </div>
<button id="hide">Hide/Show</button>

Two Html select drop down apply class for span element using Javascript

I am working on HTML select Dropdown. I have two dropdowns one is for font size adjust and other is for text alignment.
When I select the fontsize from the dropdown it has to apply along with text-capitalize (bootstrap css) and If I select the font alignment all three should apply for the span element. For Example.
<div>
<span id="Title"class="text-capitalize">check</span>
</div>
Right now the code was like this
function changeFont_size () {
var select = document.getElementById('font_size');
// Bind onchange event
select.onchange = function() {
document.querySelector("#Title").className = this.value += " text-
capitalize";
};
}
function changeAlignment () {
var select = document.getElementById('text_align');
// Bind onchange event
select.onchange = function() {
document.querySelector("#Title").className = this.value;
};
}
Actually I am newbe on Javascript. Some how I am not getting.
The output result would be the combination of :
<span class="h1 left text-capitalize">Text</span>
Everything should be in pure javascript.
Thanks in advance. Kindly help me.
Here is the Link
This jsfiddle makes your code work. You need to run the code when the document is loaded, so that your onchange functions are being hooked in time.
It does not work exactly like you intended though. Your alignment classes need to be on the parent element and when you select your alignment, you disregard the previously set h1 or h2 class.
window.onload = function() {
var font_size = document.querySelector('#font_size');
// Bind onchange event
font_size.onchange = function() {
document.querySelector("#Title").className = this.options[this.selectedIndex].value += " text-capitalize";
};
var text_align = document.querySelector('#text_align');
// Bind onchange event
text_align.onchange = function() {
document.querySelector("#Title").className = this.options[this.selectedIndex].value;
};
};
You are mixing things up. There are two ways to bind events (well, two ways which are still common even with recent browsers).
The first one is to put a function call in the onsomething property of an element in the html code. Whatever is put there will be executed when the event happens.
<button onclick="alert('hi');">Click me</button>
You should pass the event object to an event handler instead of writing inline code.
<button id="helloworld" onclick="helloworld_onclick(event)">Run</button>
...
function helloworld_onclick(e) {
alert("Hello world!");
}
If you want to be able to bind events dynamically, if you want to bind multiple events to an object and if you want to keep the JavaScript outside of your HTML, the modern way to to so is with addEventListener.
document.querySelector("#helloworld").addEventListener("click", function(e) {
alert("Hello world!");
});
The event object passed (called e in my functions) contains information about what triggered the event and can be used to prevent default behavior and to control event propagation. You can't use "this" in event handlers, but the element which called the handler will be stored in e.target.
In your code, you created functions which, when called, bind events to the elements. Then you bound those functions to the elements with the html attributes.
Finally, you seem to be stuck between querySelector and getElementById. Note that querySelector(All) returns a static node/nodelist while getElement(s)By(...) returns a live node/nodelist. A static node is a copy of all the information about the element. A live node is a reference to the real element. If you modify the element, it modifies the live node, but the static node will keep the old information. You should use getElementById over querySelector for that, and because it runs faster. For code simplicity however, you might prefer always using querySelector. Just don't mix using querySelector("#something") on a line and getElementById("something") on another one, it's the best way to get confused and end up wasting time on a bug because you wrote querySelector("something") or getElementById("#something") instead.
function changeFont_size (element) {
if(element.options[element.selectedIndex].value != 'select'){
document.getElementById('Title').className = element.options[element.selectedIndex].value;
} else{
document.getElementById('Title').className = '' }
}
function changeAlignment (element) {
if(element.options[element.selectedIndex].value != 'select'){
document.getElementById('container').className = element.options[element.selectedIndex].value;
} else{
document.getElementById('container').className = '' }
}
Try this, Hope it will work

Jquery on mousedown not working on dynamically generated elements

So i'm trying to create a js/css "wave game" like tower defense ones.
When all the pre-generated enemys from first wave are dead, it spawns the second wave and so on.
So far so good.
The problem is that i just can't attack mobs dynamically spawned within second wave.
I used to try .live() in similar cases, but its deprecated, so i'm trying .on(), as instructed
$('.enemy').on('mousedown' , function(event) {
//attack code
}
Its working fine for initial mobs (1st wave) but it still just not working on dynamic mobs (>= 2nd wave)
Help, guys, please?
You need to specify an element that is already there when the DOM is created. In the parameters, you specify the elements you want to add the mousedown method. By simply assigning $('.enemy'), it will attach the method to those that are already present in the DOM.
$('body').on('mousedown', '.enemy', function(event) {
//attack code
}
As Wex mentioned in the comments, instead of writting $('body') you should use the container's name (the container which wraps the .enemy elements. This way, when a .enemy element is added, the event doesn't need to bubble all the way up to the body tag.
The binding '.on()' works only with the content that created earlier then the script ran.
So one solution could be you bind the event to the parent element.
$('.PARENT_ELEMENT').on('mousedown', '.enemy', function(event){
// your code here
}
That should do it.
I made this google like drop down suggestions search box and I faced a problem similar to yours where there was suggestions disappearing before the re-direct happened. I overcame it by using and modifing vyx.ca answer:
var mousedownHappened = false;
var clicked_link;
$("#search-box").blur(function(e) {
if (mousedownHappened)// cancel the blur event
{
mousedownHappened = false;
window.location.href = clicked_link;
} else {
// no link was clicked just remove the suggestions box if exists
if ($('#search-btn').next().hasClass('suggestions')) {
$(".suggestions").remove();
}
}
});
//attaching the event to the document is better
$(document).on('mousedown', '.suggestions a', function() {
clicked_link= $(this).attr('href');
mousedownHappened = true;
});

Javascript two clicks - need one

I'm total beginner in JavaScript. The problem is that the code works only when I click on the text two times. I need same, but with one click. The code is on the link:
http://jsbin.com/uTizoKe/1/edit?html,output
I'd really appreciate any help. Thank in advance
Move your script tag to the end of the body of the HTML, and remove the onclick handler from the table tag. This works (here's the jsbin):
<script>
document.getElementsByTagName('table')[0].onclick = setTDOnclickEvents();
function setTDOnclickEvents() {
var allTDs = document.getElementsByTagName("TD");
for (var i in allTDs) {
allTDs[i].onclick = function () {
txtCellData.value = this.innerHTML;
}
}
}
</script>
Another option (rather than calling your function based on a table click) is to simply do this:
<script>
var allTDs = document.getElementsByTagName("TD");
for (var i in allTDs) {
allTDs[i].onclick = function () {
txtCellData.value = this.innerHTML;
}
}
</script>
Another option is (if you want to use the script in the head of the document), put everything as a function inside of window.onload.
Additionally, it generally a good practice to try to avoid relying on putting event handlers inside HTML elements themselves, and rather handle all that stuff inside your JavaScript.
Remove the onclick from the table and add it as onload to the body
DEMO
Alternatively, you can use window.onload instead of putting it directly in the body
DEMO
The problem is that you have an onclick attached to the table which calls setTDOnclickEvents. So, only when the user clicks the table will that onclick occur.
What you really want is to bind your elements within the table when the page loads. Using jQuery you could do...
$(function() {
setTDOnclickEvents();
});
Replace
<body>
by
<body onload="setTDOnclickEvents()">
There are other ways to do that, like you could just write :
document.onload = setTDOnclickEvents;
Inside your JavaScript
You need to bind your function to an event for it to be fired at all, if it's inside head.
I'd expect your code not to work at all, strange that it does. Perhaps some default behavior somewhere, not worth investigating...
PS: I just saw that you're biding the click event for table to the function, so that would explain the strange behavior. Yeah, remove that.
The problem is that you're calling setTDOnclickEvents() on click of the table element. So you're not attaching the click events until after you've clicked the first time.
Instead, you can move this into the body onload attribute.
There are some other improvements you could make to this code to, to make it simpler and more up-to-date. If interested, please let me know, I'd be happy to help.

How do I inherit jQuery effects when i introduce a new DOM

I have a slideshow that i replace an unordered list within the slide show, the images change but any effects are not inherited. this is the script that introduces a new DOM:
jQuery("#kwick1").click(function () {
jQuery('#photography').load('/design.html #photography');
});
jQuery("#kwick2").click(function () {
jQuery('#photography').load('/design.html #design');
});
how do i get the jQuery slideshow to inherit this new list of images??
i both these functions and the slide show function in the same file.
I have a
jQuery(document).ready(function() {
that loads the slideshow script.
You have to let us know what slideshow plugin you are using. Regardless, you probably just need to destroy your old slideshow instance and restart it. Something like:
//start slideshow on
var slideshow = $('#slideshow').cycle();
slideshow.start();
$('#button').click( function() {
//depending on plugin api maybe stop, add and start again
slideshow.stop();
slideshow.addImages();
slideshow.start();
//or perhaps just destroy old slideshow and restart
slideshpw = $('#slideshow').cycle();
});
To attach events to newly added elements you should use live() or delegate();
jQuery('.yourselector').live('click', function(){
//do something on click
});
Instead of attaching events to each of elements, you should learn how to use event delegation. That way you can attach single event listener on some container ( or even document ) and catch the events as they bubble up.
Additionally it will make your code look much cleaner and easier to understand.
http://lab.distilldesign.com/event-delegation/
http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-event-delegation-in-4-minutes/
http://www.sitepoint.com/javascript-event-delegation-is-easier-than-you-think/
P.S. , if you put your code at the bottom of the HTML ( before </body> ) then, when it triggers , it will already be an "onDomReady" event.

Categories

Resources