Can this JQuery code be written using plain Javascript? - javascript

Is there a way to represent this code as plain vanilla Javascript so I can better understand how it works for now?
$("#id").click(function(){
var $x = $("#id");
$x.removeProp("-webkit-animation");
});
Essentially I'm using this to tell the code not to play a css animation given that a certain set of parameters are met.

removeProp removes properties of objects. If that’s definitely what you want, the equivalent is the delete operator:
var element = document.getElementById("id");
element.addEventListener("click", function () {
delete element["-webkit-animation"];
});
If what you really want to do is change a CSS property, though, it needs to be an operation on the element’s style:
element.style.WebkitAnimation = "none";
But what you should probably do is change a class instead:
element.classList.add("no-animation");
and use CSS:
.no-animation {
-webkit-animation: none;
}

The delete element is the somewhat equivalent on vanilla javascript of removeProp()
element = document.getElementById('id');
element.onclick() = function(){
delete element['-webkit-animation'];
}

Yes, you can use the .removeAttribute() function to remove an attribute, like style, title, etc.
Or you can use .removeProperty() to remove a style property (supported in IE9 and above)
Fiddle
(function() {
var myDiv = document.getElementById('myDiv');
myDiv.removeAttribute('style');
var aDiv = document.getElementById('aDiv');
aDiv.style.removeProperty('height');
})();
<div id="aDiv" style="background-color: green;">Hi</div>
<div id="myDiv" style="background-color: green;">Hi</div>

Hope it will help OP
JS
var element = document.getElementById("id");
element.onClick = function(){
this.style.removeProperty("-webkit-animation");
};

Related

Javascript onClick event not working to log on the console

I know I'm overlooking something but I'm stuck on knowing what I'm doing wrong. Can't seem to get the console to print out ( I'm eventually working on adding a box to the screen). I'm using Chrome btw:
HTML
<button id="1" class="hot"></button>
JS
function addBox() {
console.log("hello");
}
var clickBox = document.getElementById("1");
clickBox.onClick = addBox;
DOM properties are case sensitive (unlike HTML attributes) and the correct name of the property is onclick:
clickBox.onclick = addBox;
Learn more about the different ways of binding event handlers.
function addBox() {
console.log("hello");
}
var clickBox = document.getElementById("1");
clickBox.onclick = addBox;
.hot {
width: 100px;
height: 100px;
border: 3px solid black;
background-color: pink;
}
<button id="1" class="hot"></button>
Try
clickBox.onclick = addBox;
or
clickBox.addEventListener('click', addBox);
I do not know of any native onClick method for DOM elements in JavaScript.
You could do an event attribute in your HTML <button onclick="addBox()">.
Or you could do clickBox.addEventListener('click', addBox);.
this this code javascript :
var clickBox = document.getElementById("1");
clickBox.onclick=addBox;
function addBox() {
console.log("hello");
}
First, your ID should begin with a letter (if you plan to have HTML4 compatibility). Second, if you want to define an event using JS (without a library such as jQuery), you should use addEventListener. Or you can simply go the route of adding onclick directly to the element (onclick="addBox()"). Finally your onclick should all be lowercase (as JS property keys are case sensitive).
Try giving all the javascript within window.onload tags
Like the following:
window.onload = function(){
//Your Code Here
}

A function to remove specified elements

I need to create a function which gets user input (a css selector) and removes all of those elements.
This is the function so far
function removeBySelector(selector) {
var thisOne = document.querySelectorAll(selector);
for(var i = 0; i<thisOne.length; i++) {
document.removeChild(thisOne[0]);
};
};
and the HTML that starts it
<button type="button" name="button" onclick="removeBySelector(prompt('Type the selector e.g p/ p.pClass'));">Remove By Selector</button>
change your method to
function removeBySelector(selector)
{
var thisOne = document.querySelectorAll(selector);
for(var i = 0; i<thisOne.length; i++)
{
thisOne[i].parentNode.removeChild( thisOne[i] ); //changed parentElement to parentNode
};
}
i'd advise using the framework jQuery! It is a very powerful tool that helps you simplify and improve your JavaScript code and it's performance.
With jQuery you can easily use this piece of code to remove any elements by CSS selector.
// Use any CSS Selector here
var elements = $(".class");
$.each(elements, function(){
$(this).remove();
)};
This keeps your code very easy to read and has a high performance.
//Try this code:
var removeElement=function(selector){
$(document).find(selector).remove();
};
removeElement('h1'); // will remove all H1 elements from Document.
You can do the same, without using any library with pure javascript (ES6 syntax in this case):
let elements = document.querySelectorAll(".please-remove");
elements.forEach(e => e.remove());
<div>
<div class="keep">Keep this element</div>
<div class="please-remove">1</div>
<div class="please-remove">2</div>
<div class="please-remove">3</div>
<div class="please-remove">4</div>
<div class="please-remove">5</div>
<div class="please-remove">6</div>
</div>

getElementById with changing IDs

I need to hide all the elements that have the string "replies-36965584" anywhere in their IDs.
HTML:
<div id="replies-36965584_1">aaaa</div>
<div id="replies-36965584_2">aaaa</div>
<div id="replies-36965584_3">aaaa</div>
<div id="replies-36965584_4">aaaa</div>
<div id="replies-36222224_2">nnnn</div>
JavaScript:
document.getElementById("replies-36965584").style.display="none"
How can I modify this JS to select the first four elements?
You can do this with CSS and attribute selectors.
[att^=val]
Represents an element with the att attribute whose value begins with the prefix "val". If "val" is the empty string then the selector does not represent anything.
Source: http://www.w3.org/TR/css3-selectors/#attribute-substrings
jsfiddle
CSS
[id^="replies-36965584_"] {
display: none;
}
Is using jQuery an option? If so, this is dead simple:
$(document).ready(function(){
$('div[id^="replies-36965584"]').hide();
});
If you're unfamiliar with jQuery, here's a link to get started: http://learn.jquery.com/javascript-101/getting-started/
EDIT: Fixed syntax error.
EDIT: Added jsFiddle: http://jsfiddle.net/xbVp9/
If you don't know certain literal values but you know the general pattern and only the number will change, then I will consider some matching with regular expresiion.
You can do it the painful way:
var o = document.getElementsByTagName("div");
for (var i=0;i<o.length;i++) {
if(o[i].id.indexOf('replies-36965584') == 0) {
o[i].style.display = 'none';
}
}
The only way to do this with vanilla javascript that I know of, is to fetch all the divs on the page, and test the id's for the ones you want.
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; ++i) {
var div = divs[i];
if (/replies-36965584/.test(div.id)) {
div.style.display = 'none';
}
}

Using $(this) in setTimeout();

I want to set timeouts dynamically in jQuery. The dynamically set timeout functions need to use $("this"), but I can't seem to get it working.
An exmple:
$("div").each(function(){
var content = $(this).attr('data-content')
setTimeout("$(this).html('"+content+"')",$(this).attr('data-delay'));
});​
http://jsfiddle.net/qmhmQ/
What is the best way to do this?
$("div").each(function(){
var content = $(this).attr('data-content'),
$this = $(this); // here $this keeps the reference of $(this)
setTimeout(function() {
// within this funciton you can't get the $(this) because
// $(this) resides within in the scope of .each() function i.e $(this)
// is an asset of .each() not setTimeout()
// so to get $(this) here, we store it within a variable (here: $this)
// and then using it
$this.html(content);
}, $this.attr('data-delay'));
});​
DEMO
Your code should look like this:
pass a function instead of a string.
Explanation:
When passing a string to setTimeout you get problems, because it runs in a different scope than you original one, and thus you get errors.
use the jQuery data()method
$("div").each(function(){
var content = $(this).attr('data-content'),
$el = $(this),
setContent = function(){
$el.html(content);
}
setTimeout(setContent,$el.data('delay'));
});​
You can assign a function to a variable and pass that variable as parameter to setTimeout, this is the cleanest way.
Use closures (some tutorials).
Using strings with setTimeout is not a good idea. Also beware this, since it can change its context (ie. call-site) if used inside a closure.
If using data attributes you can use the jQuery data function.
$("div").each(function() {
var instance = $(this);
var content = instance.data('content');
var method = function() {
instance.html(content);
};
setTimeout(method, instance.data('delay'));
});
div {
border: 1px solid black;
margin: 5px;
height: 1.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-content="fus" data-delay="1000"></div>
<div data-content="ro" data-delay="2000"></div>
<div data-content="dah" data-delay="5000"></div>
I am just expanding answer one above,
Use class or id to refer div in JavaScript. This will avoid further tag name conflicts in the page.
So your updated HTML is,
<div data-content="fus" data-delay="1000" class="dv"></div>
<div data-content="ro" data-delay="2000" class="dv"></div>
<div data-content="dah" data-delay="5000" class="dv"></div>​
Now your updated JavaScript code is,
$(".dv").each(function(){
var content = $(this).attr('data-content'),
$this = $(this);
setTimeout(function() {
$this.html(content);
}, $this.attr('data-delay'));
});​
Where main line is
$this = $(this);
Where we are assigning the current element to our variable used in the setTimeout function.
Please refer this link
Take $(this) out of settimeout and save that in local variable say 'self' just after $("div").each(function(){ this line
var self=$(this);
and use that self further.
The following seems like a good compromise of whitespace, readability and revealing intention.
$('div').each(function(){
var element = $(this)
var content = element.attr('data-content')
var delayms = element.attr('data-delay')
var action = function() { element.html(content) }
setTimeout(action, delayms)
})
​
SEE: http://jsfiddle.net/wilmoore/LSs6g/

how to make div click-able?

<div><span>shanghai</span><span>male</span></div>
For div like above,when mouse on,it should become cursor:pointer,and when clicked,fire a
javascript function,how to do that job?
EDIT: and how to change the background color of div when mouse is on?
EDIT AGAIN:how to make the first span's width=120px?Seems not working in firefox
Give it an ID like "something", then:
var something = document.getElementById('something');
something.style.cursor = 'pointer';
something.onclick = function() {
// do something...
};
Changing the background color (as per your updated question):
something.onmouseover = function() {
this.style.backgroundColor = 'red';
};
something.onmouseout = function() {
this.style.backgroundColor = '';
};
<div style="cursor: pointer;" onclick="theFunction()">
is the simplest thing that works.
Of course in the final solution you should separate the markup from styling (css) and behavior (javascript) - read on it on a list apart for good practices on not just solving this particular problem but in markup design in general.
The simplest of them all:
<div onclick="location.href='where.you.want.to.go'" style="cursor:pointer"></div>
I suggest to use jQuery:
$('#mydiv')
.css('cursor', 'pointer')
.click(
function(){
alert('Click event is fired');
}
)
.hover(
function(){
$(this).css('background', '#ff00ff');
},
function(){
$(this).css('background', '');
}
);
I suggest to use a CSS class called clickbox and activate it with jQuery:
$(".clickbox").click(function(){
window.location=$(this).find("a").attr("href");
return false;
});
Now the only thing you have to do is mark your div as clickable and provide a link:
<div id="logo" class="clickbox"></div>
Plus a CSS style to change the mouse cursor:
.clickbox {
cursor: pointer;
}
Easy, isn't it?
add the onclick attribute
<div onclick="myFunction( event );"><span>shanghai</span><span>male</span></div>
To get the cursor to change use css's cursor rule.
div[onclick] {
cursor: pointer;
}
The selector uses an attribute selector which does not work in some versions of IE. If you want to support those versions, add a class to your div.
As you updated your question, here's an obtrustive example:
window.onload = function()
{
var div = document.getElementById("mydiv");
div.style.cursor = 'pointer';
div.onmouseover = function()
{
div.style.background = "#ff00ff";
};
}
<div style="cursor: pointer;" onclick="theFunction()" onmouseover="this.style.background='red'" onmouseout="this.style.background=''" ><span>shanghai</span><span>male</span></div>
This will change the background color as well
If this div is a function I suggest use cursor:pointer in your style like style="cursor:pointer" and can use onclick function.
like this
<div onclick="myfunction()" style="cursor:pointer"></div>
but I suggest you use a JS framework like jquery or extjs

Categories