How to convert JavaScript code to jQuery? - javascript

symbolen.parent = object;
object.element.onclick = function() {
this.parent.position.x = 0;
this.parent.position.y = 0;
this.parent.position.z = 0;
this.parent.scale.x = 4,
this.parent.scale.y = 4;
};
i want to convert the javascript code to jquery.
Because i want to use "siblings".
how can i change it ?
is there any website for that?
for example i tried this code with scale first , there is no error message, but it is not working...
$('object').click(function(event) {
$(this).parent().css('scale', '4');
$(this).parent().siblings().css('scale', '0');
event.preventDefault();
});

You can wrap element(s) in a jQuery object with $(element). Then you can do any jQuery functionality with it. I changed 'object' selector into object.element. You don't use quotes here because you use the element in the variable directly instead of using a selector. Also scale is not a css attribute so i assume you mean transform: scale()
//Mimic your object.element
var object = {};
object.element = document.getElementsByClassName('scale');
//Add on click handler and set scale on click.
$(object.element).click(function() {
$(this).css("transform", "scale(4, 4)");
$(this).siblings().css("transform", "scale(1)");
});
div#parent {
text-align: center;
}
div#scale {
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
<br>
<div class="scale">Scale on click</div>
<br>
<br>
<br>
<div class="scale">Scale on click</div>
<br>
</div>

Related

Anchor Tag href functions

I am trying to create a function that finds the id of an element that an anchor tag directs to, and attach a class to that element. I need this to be vanilla js not jquery.
For Example:
<div id="firstDiv"></div>
<div> Destination </div>
<div> Destination #2 </div>
The idea would be that once you click on the anchor tag that it would take you to the div and attach a class to that div to initiate a function.
The script that I've written runs for loops that add the values of the href attribute and the id attribute from javascript objects. See Below:
var rooms = [
{
id: 1,
name: Example,
},
{
id:2,
name: Example #2,
}
]
for ( x in rooms ) {
var i = document.getElementById("firstDiv");
var a = document.createElement("a");
i.appendChild(a);
a.href = "#" + rooms[x].id;
a.innerHTML += rooms[x].name + "<br>";
a.classList.add("show");
}
var rect = document.getElementsByTagName("rect");
for ( i = 0; i < rect.length; i++ ) {
rect[i].setAttribute("id", rooms[i].id);
}
Output:
<div id="firstDiv">
Example
Example #2
</div>
<div id="1"> Destination </div>
<div id="2"> Destination #2 </div>
The function below is an example of what I want the function to do for each corresponding div when an a tag is clicked.
function attach() {
var div = document.getElementById(rooms[i].id);
div.classList.toggle("active");
}
Any advice on how to properly write this function for my particular needs. Would a for loop be best for this or an if/else statement. I've tried both but neither has worked.
Please let me know if I need to clarify more.
It seems like this is what you are asking about. See comments inline.
document.addEventListener("click", function(event){
// First, check to see if it was an anchor that was clicked
// in the document
if(event.target.nodeName === "A"){
// If so, add a class to the target
// Get the href attribute and strip off the "#", then find that element and toggle the class
document.getElementById(event.target.getAttribute("href").replace("#","")).classList.toggle("highlight");
}
});
.highlight { background-color:yellow; }
<div id="firstDiv">
Example
Example #2
</div>
<div id="one"> Destination </div>
<div id="two"> Destination #2 </div>
Try this:
let anchors = document.querySelectorAll("#firstDiv a");
for (let i = 0; i < anchors.length; i++) {
anchors[i].addEventListener("click", () => {
var div = document.getElementById(rooms[i].id);
div.classList.toggle("active");
}
You're almost there you just need to add an onclick property for the anchor tag now you can or cannot use the third attach function.I am including both implementations for your reference.
for ( x in rooms ) {
var i = document.getElementById("firstDiv");
var a = document.createElement("a");
i.appendChild(a);
a.href = "#" + rooms[x].id;
a.innerHTML += rooms[x].name + "<br>";
a.classList.add("show");
a.onClick=`document.getElementById(${rooms[x].id}).classList.toggle("active")`;
}
If you want to have a dedicated function your loop becomes
for ( x in rooms ) {
var i = document.getElementById("firstDiv");
var a = document.createElement("a");
i.appendChild(a);
a.href = "#" + rooms[x].id;
a.innerHTML += rooms[x].name + "<br>";
a.classList.add("show");
a.onClick=`attach(${rooms[x].id})`;
}
Your attach function then becomes:
function attach(id) {
var div = document.getElementById(id);
div.classList.toggle("active");
}
Do let me know if you have any issues.
CSS Only 😎
This is a bit off-topic but you can use the :target selector to set the style of the corresponding id without JS.
/* element with an id matching the URL fragment */
:target {
background: gold;
}
/* you can combine target with other selectors */
#c:target {
background: orange
}
/* just a bit of styling */
a,div {
padding: .5rem;
display: block;
width: 20%;
float:left;
}
Link to A
Link to B
Link to C
Link to D
<div id="a">A</div>
<div id="b">B</div>
<div id="c">C</div>
<div id="d">D</div>

JavaScript: Select multiple elements by z-index number (in dynamic DOM)

I would like to select ALL elements in DOM that have the z-index = 2147483647 using 100% JavaScript (NO jQuery)
The DOM is constantly dynamically changing; adding and removing
elements. The code to remove elements by z-index ### MUST have a DOM event listener
I've tried so many iterations of similar codes without success. This is my last iteration attempt and for some reason it is not working
window.addEventListener('change', function() {
var varElements = document.querySelectorAll("[style='z-index: 2147483647']");
if(varElements) { for(let varElement of varElements) { varElement.remove(); } }
} //function
}) //window.
check below code
const check = () => {
var varElements = document.querySelectorAll("*");
for(let varElement of varElements) {
if(varElement.style['z-index'] == 10) {
var node = document.createElement("LI");
var textnode = document.createTextNode(varElement.className);
node.appendChild(textnode);
document.getElementById('list').appendChild(node)
}
}
}
window.addEventListener('change', check )
window.addEventListener('load', check);
<div class="top" style="z-index:10">
<div class="inner1" style="display:'block';z-index:10">
<div class="inner2" style="z-index:10">
</div>
</div>
<div class="inner3" style="z-index:12">
</div>
</div>
<ul id="list">
</ul>
There are some things that come into play here i.e. it has to be positioned to get a z-index. Here I show some examples and how to find stuff that has a z-index not "auto";
You can then loop the list to find a z-index you desire. Here, I just pushed all elements with a z-index not "auto" but you could use your selected index value to filter those out in the conditional for example if (!isNaN(zIndex) && zIndex != "auto" && zIndex == 4042) for those with 4042 value;
Once you have your elements, you can do what you desire which is to set an event handler on each of them.
This specifically answers the question of finding the elements by z-index, not the ultimate desire which is another question of how to manage the changes to the DOM and adding/removing on mutation.
var getZIndex = function(checkelement) {
let compStyles = window.getComputedStyle(checkelement);
let z = compStyles.getPropertyValue('z-index');
if (typeof z == "object" || (isNaN(z) && checkelement.parentNode != document.body)) {
return getZIndex(checkelement.parentNode);
} else {
return z;
}
};
let evallist = document.querySelectorAll("div");
let zthings = [];
for (let item of evallist) {
let zIndex = getZIndex(item);
if (!isNaN(zIndex) && zIndex != "auto") {
zthings.push(item);
}
}
console.log(zthings);
.sureThing {
z-index: 4242;
position: absolute;
background: gold;
top: 4em;
}
<div class="mything">Howddy</div>
<div class="sureThing">Here I am</div>
<div class="onelink">https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle</div>
<div class="otherthing" style="z-index:4040;">other thing set internal woops Ihave no position so I am not in list</div>
<div class="otherthing" style="z-index:4040;position: absolute;top:5em;">other thing set internal OK</div>
You cannot select an element based on css in css. So you cannot use the querySelectorAll. This code works if the css is set by the inline style attribute. Here is the code explained:
Get all element using *.
Turn the NodeList into an array.
Filter out the elements that do not have a specific css property.
get the css properties using: window.getComputedStyle()
window.addEventListener( 'load', () => {
let all = document.querySelectorAll('*');
all = Array.from(all);
const filtered = all.filter( zindex_filter )
console.log( filtered )
})
function zindex_filter (element) {
const style = window.getComputedStyle(element);
console.log( style.getPropertyValue('z-index') )
if( style.getPropertyValue('z-index') == 100 ) return true;
else return false;
}
.div {
width: 100px;
height: 100px;
margin: 10px;
}
.zindex {
position: relative;
z-index: 100;
}
<div class='zindex div'></div>
<div class='div'></div>
<div class='div' style='position: relative; z-index: 100; width: 100px;'></div>
Notes:
window.getComputedStyle() docs
note that the z-indexed must be positioned correctly to return a value other than auto.

Multiple div selection onclick

I have multiple divs with their id's, and onclick i store the id of the div in an input value, but it only takes one id, i want to have multiple selection and store all the selected div id's in the same input, here is my code:
function storeId (el) {
$('input').val(el.id);
}
div{
background-color:red;
height: 50px;
width: 50px;
margin-bottom: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div-1" onclick="storeId(this);">
</div>
<div id="div-2" onclick="storeId(this);">
</div>
<div id="div-3" onclick="storeId(this);">
</div>
<div id="div-4" onclick="storeId(this);">
</div>
<input>
Instead of setting the input's value directly, store the id in an array and then upon each click, update the input with the array's contents.
Also, don't use inline HTML event attributes. There are many reasons not to use this ancient technique that just will not die.
let ids = [];
$("div").on("click", function(){
// If the id is not already in the array, add it. If it is, remove it
ids.indexOf(this.id) === -1 ? ids.push(this.id) : ids.splice(ids.indexOf(this.id),1);
$('input').val(ids.join(", ")); // populate the input with the array items separated with a comma
});
div{
background-color:red;
height: 50px;
width:50px;
margin-bottom: 15px;
display:inline-block; /* Just for the SO space */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div-1"></div>
<div id="div-2"></div>
<div id="div-3"></div>
<div id="div-4"></div>
<input>
You have two options based on your requirements:
Append newly clicked id's to the existing value of your input.
Push newly clicked id's into an array which is used to build the value of your input.
Option 1
function storeId (el) {
var currentValue = $('input').val();
$('input').val(currentValue + ', ' + el.id);
}
(Or with newer syntax)
function storeId (el) {
const currentValue = $('input').val();
$('input').val(`${currentValue}, ${el.id}`);
}
Option 2
var storedIds = [];
function storeId (el) {
var index = storedIds.indexOf(el.id);
if (index === -1) {
storedIds.push(el.id);
} else {
storedIds.splice(index, 1);
}
$('input').val(storedIds.join(', '));
}
Edit: Only the array example above checks if the id being stored has already been stored or not.
Please try it:
function storeId (el) {
if ($('input').val().indexOf(el.id) >= 0){
$('input').val($('input').val().replace(el.id + ",", ""));
return
}
$('input').val($('input').val() + el.id + ",");
}

Append new Element only once on click and save it to local storage html javascript

Here is JS Fiddle!
I am trying to append new Elements to the div, this is working.
My problem is that I want to append the new element only once on button click, and save it to localStorage so that I would not loose the state on refresh or any other action.
div {
text-align: center;
}
#Neighborhood {
color: brown;
}
#NewElement {
color: green;
}
<div id="Neighborhood">
<div id="Neighbor1">Neighbor 1</div>
<div id="Neighbor2">Neighbor 2</div>
<div id="Neighbor3">Neighbor 3</div>
</div>
<input type="button"onclick="add_prev();" value="ACTION">​
/* Adds Element BEFORE NeighborElement */
Element.prototype.appendBefore = function (element) {
element.parentNode.insertBefore(this, element);
}, false;
/* Adds Element AFTER NeighborElement */
Element.prototype.appendAfter = function (element) {
element.parentNode.insertBefore(this, element.nextSibling);
}, false;
/* Typical Creation and Setup A New Orphaned Element Object */
add_prev = function () {
var NewElement = document.createElement('div');
NewElement.innerHTML = 'New Element';
NewElement.id = 'NewElement';
NewElement.appendBefore(document.getElementById('Neighbor2'));
}
I am thankful for every tip or solution! Cheers!
Pass this to the onclick function. That way, after you do your things, just remove the listener to click or disable the button.
Also, when the page loads, load the information from the storage, if it's true, directly call the function and then disable the button.
Maybe it isn't exaclty what you need, but it can help a lot, you can follow this logic to get there. The code below is just an example.
OBS: it won't work well here because localStorage is not allowed in StackOverflow.
In this fiddle you can try it better: https://jsfiddle.net/so5u1c4z/
On the fiddle above, create the element, then save and reload the page. the element will be there once the page loads.
$(document).ready(function(){
add_prev = function (elem) {
var NewElement = document.createElement('div');
NewElement.innerHTML = 'New Element';
NewElement.id = 'NewElement';
document.getElementById('Neighbor2').append(NewElement);
localStorage.setItem('elementCreated', true);
if (elem){
$(elem).attr('disabled', true);
}
}
var isCreated = localStorage.getItem('elementCreated');
if (isCreated){
add_prev();
$("#btnAdd").attr('disabled', true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" onclick="add_prev(this);" value="ACTION" id="btnAdd">
<div id="Neighbor2"></div>

Change font size of all elements inside a div

I have following page in which there is a div menu. Inside menu we can have <table>, <p>, <h>. Different elements for example:
<div id="menu">
<p>abc def</p>
<table>
<tr><td>helloo </td><tr>
<tr><td>hiii </td><tr>
</table>
<div id="sub"><p>123 this is test</p></div>
</div>
Is there a way to change size of all text in between elements inside menu. For example: abc def, hellooo, hiii, 123 this is test. Can i change all that text using jquery or javascript some how.
Yes you can use JavaScript and or jQuery to do what you want, but why wouldn't you just use CSS like suggested?
or you can try this:
<Style>
/*Assumed everything is inheriting font-size*/
#menu{
font:12px;
}
/* Force all children to have a specified font-size */
#menu *{
font:14px;
}
</style>
<script>
//JavaScript
document.getElementById('menu').style.fontSize = "14px";
//jQuery
$("#menu").css({'font-size':'14px'});
</script>
You can do this with css:
#menu {
font-size: XXX;
}
jQuery Example
$('#menu').nextAll().css('font', '14px');
Take a look at this:
http://jsfiddle.net/oscarj24/jdw6K/
Hope this helps :)
var VINCI = {};
VINCI.Page = {
init : function() {
this.initFontResize();
},
initFontResize : function() {
var container = $('#menu, #sub');
var originalFontSize = parseFloat(container.css('font-size'), 10);
var size_level = 0;
var maximum_size_level = 5;
var size_change_step = 1.4;
function calculateFontSize()
{
return originalFontSize + (size_level * size_change_step);
}
// Increase Font Size
$('.increaseFont').click(function(){
if (size_level < maximum_size_level) {
size_level++;
container.stop().animate({'font-size' : calculateFontSize()});
}
return false;
});
// Decrease Font Size
$('.decreaseFont').click(function(){
if (size_level > 0) {
size_level--;
container.stop().animate({'font-size' : calculateFontSize()});
}
return false;
});
};
VINCI.Page.init();

Categories

Resources