Set CSS property with pure JS, display:none - javascript

I need to hide a <section> in my HTML with JavaScript while highlighting the text or to show it otherwise.
My selection works in this way:
document.addEventListener('click', function(){
var selected = window.getSelection();
var links = document.getElementsByClassName("linkAnnotation");
if (selected == '') {
links.setAttribute('style', 'display:block;');
} else {
links.setAttribute('style', 'display:none;');
}
})
but this setAttribute does not work as other hundreds of tries that I have done.
Can someone save my life??
Every setAttribute, style.innerHTML, etc.

when you are selecting links it retuns HTMLCollection forExample : [linkAnnotation1, linkAnnotation2] it not returns one element because your code doesnot works you must write for loop example:
document.addEventListener('click', function () {
var selected = window.getSelection();
var links = document.getElementsByClassName('linkAnnotation')
if (selected == '') {
for (let i = 0; i <= links.length - 1; i++) {
links[i].setAttribute('style', 'display:block')
}
}else {
for(let i = 0; i <= links.length - 1; i++) {
links[i].setAttribute('style', 'display:none')
}
}
})

getElementsByClassName returns a HTMLCollection (Which returns an array-like object of all child elements which have all of the given class name(s)). You have to iterate through all of those elements and change properties.
So, you have to use the following code:
document.addEventListener('click', function() {
var selected = window.getSelection();
var links = document.getElementsByClassName("linkAnnotation");
if (selected === '') {
links.forEach(val => { val.setAttribute('style', 'display:block;'); });
} else {
links.forEach(val => { val.setAttribute('style', 'display:none;'); });
}
})

Related

Live search results clickable using AJAX

I am able to search and display the results that the user is typing on the keyup function. But now when the results show up inside my <div> tag, they are not clickable. Is there a way I can make them clickable and also allow the user to select multiple results from the live search results. This is what I tried so far.
HTML
<input type="text" id ="medication" name="medication" onkeyup="getsearch(this.value)"><br>
<div id="livesearch"></div>
JavaScript
function getsearch(val) {
results = [];
document.getElementById("livesearch").innerHTML = "";
if (val.length == 0) {
document.getElementById("livesearch").innerHTML = "";
document.getElementById("livesearch").style.border = "0px";
return;
}
console.log(s);
console.log("val", val);
if (val.length > 2) {
for (var i = 0; i < s.length; i++) {
for (key in s[i]) {
if (s[i][key].indexOf(val) != -1) {
$("#livesearch").append(s[i][key]);
$("#livesearch").append("<br/>");
results.push(s[i]);
}
}
}
}
console.log(results);
};
There are some other thing I would do differently here, but as far as what you are looking to do this should work.
if(val.length>2) {
for (var i = 0; i < s.length; i++) {
for (key in s[i]) {
if (s[i][key].indexOf(val) != -1) {
var newDom = $('<div><\div>'); //create a DOM element to wrap each of the return text in.
newDom.text(s[i][key]);
$("#livesearch").append(newDom);
results.push(s[i]);
}
}
}
}
Then you can assign the click event to you dynamically created DOM this way.
$('#livesearch').on('click', 'div', myDoStuffFunc);
function myDoStuffFunc(){
// this is fired from the click event
}

How to compare 2 DOM elements?

I want to alert b if element is $("[id$=linkbuttonabsd]") and alert a otherwise.
JavaScript code:
$("body").find("a").click(function (e) {
var herf = $("body").find("a");
var link = $("[id$=linkbuttonabsd]");
var isb = false;
for (var i = 0; i < herf.length; i++) {
if (herf[i] == link) {
isb = true;
}
}
if (isb) {
alert("b");
} else {
alert("a");
}
});
But I can not achieve this by herf[i] == link. How should it be done?
$.fn.is() can be used.
Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
if(herf.eq(i).is(link)){
//Condition is ture
}
Also to get the element at specified index use .eq() rather than []
You don't need to loop through the objects. Code can be reduced to
$("body a").click(function(e) {
var herf = $("body a");
var link = $("[id$=linkbuttonabsd]");
var isb = herf.is(link);
if (isb) {
alert("b");
} else {
alert("a");
}
});
Try using $.is to match an element. Here is the example:
if ($(herf[i]).is("#linkbuttonabsd")) {
isb = true;
}

Need a better way to mass modifying css Class

I have a huge collection of list elements.
the concept is that the user can select only two items from that collection.
I am showing a check/Uncheck as an image infront of the list item, just for visual purposes that the list is selected or not.
The image is defined in a class, so I have to switch classes to show selected or unselected.
This is they way I am currently modifying the class but I think it might be too heavy.
function showAsSelected(selectedArr, selectedCat) {
var allLinks = document.getElementsByClassName("linkRef");
var len = allLinks.length;
for (var i = 0; i < len; i++) {
allLinks[i].setAttribute('class', 'linkRef subCategLink');
}
for (var i = 0; i < selectedArr.length; i++) {
selectedArr[i].setAttribute('class', 'linkRef subCategLinkChkd');
}
}
'allLinks' gets all the elements having class "linkRef". counting above 100 sometimes. The first loop modifies class to 'linkRef subCategLink'. This means it will remove 'subCategLinkChkd' from two elements (Running a loop on hundreds only to modify two).
The second loop sets the class only on the two elements which are referenced in the "selectedArr" array.
I assuming that you have a similar HTML structure (and if so) you can try something like this.
jsFiddle
(function () {
"use strict";
var list = document.getElementById("list"),
selectedInputs = [],
shifted = null;
list.addEventListener("change", function (e) {
var target = e.target,
index = selectedInputs.indexOf(target);
if (target.nodeName.toLowerCase() === "input" &&
target.type.toLowerCase() === "checkbox" &&
target.classList.contains("linkRef")) {
if (target.checked && index === -1) {
target.setAttribute('class', 'linkRef subCategLinkChkd');
selectedInputs.push(target);
} else if (target.checked === false && index !== -1) {
selectedInputs.splice(index, 1);
target.setAttribute('class', 'linkRef subCategLink');
}
if (selectedInputs.length > 2) {
shifted = selectedInputs.shift();
shifted.setAttribute('class', 'linkRef subCategLink');
shifted.checked = false;
}
}
}, false);
}());
Updated

Hiding all elements with the same class name?

I'm trying to hide elements with the same class name (float_form), but I'm also trying to use the script below to show them (all of the float_form class divs are initially hidden). I've looked at a lot of jquery solutions, but I can't seem to make any of them work for this.
function show(a) {
var e = document.getElementById(a);
if (!e)
return true;
if (e.style.display == "none") {
e.style.display = "block"
} else {
e.style.display = "none"
}
return true;
}
​
Edit: Sorry if it wasn't clear, I do not intend to use Jquery(and I know that this is not jquery). I am looking for a way to use javascript to recognize repeated classnames that are not in style= display:none; without compromising the show/hide ID element since there is a loop with the div id as the key. The html for the div looks like below, with {item.ID} being a while loop.
<div class="float_form" id="{item.ID}" style="display: none;">
vanilla javascript
function toggle(className, displayState){
var elements = document.getElementsByClassName(className)
for (var i = 0; i < elements.length; i++){
elements[i].style.display = displayState;
}
}
toggle('float_form', 'block'); // Shows
toggle('float_form', 'none'); // hides
jQuery:
$('.float_form').show(); // Shows
$('.float_form').hide(); // hides
If you're looking into jQuery, then it's good to know that you can use a class selector inside the parameters of $ and call the method .hide().
$('.myClass').hide(); // all elements with the class myClass will hide.
But if it's a toggle you're looking for, use .toggle();
But here's my take on a good toggle without using jQuery:
function toggle( selector ) {
var nodes = document.querySelectorAll( selector ),
node,
styleProperty = function(a, b) {
return window.getComputedStyle ? window.getComputedStyle(a).getPropertyValue(b) : a.currentStyle[b];
};
[].forEach.call(nodes, function( a, b ) {
node = a;
node.style.display = styleProperty(node, 'display') === 'block' ? 'none' : 'block';
});
}
toggle( '.myClass' );
Demo here (Click "Render" to run): http://jsbin.com/ofusad/2/edit#javascript,html
Using jquery
$(".float_form").each(function(){
if($(this).css("display") == "none"){
$(this).show();
}else{
$(this).hide();
}
});
No jQuery needed
const toggleNone = className => {
let elements = document.getElementsByClassName(className)
for (let i = 0; i < elements.length; i++){
if (elements[i].style.display === "none") {
elements[i].style.display = "";
} else {
elements[i].style.display = "none";
}
}
}
const toggleVisibility = className => {
let elements = document.getElementsByClassName(className)
for (let i = 0; i < elements.length; i++){
let elements = document.getElementsByClassName(className);
if (elements[i].style.visibility === "hidden") {
elements[i].style.visibility = "";
} else {
elements[i].style.visibility = "hidden";
}
}
}
// run
toggleNone('your-class-name-here'); // toggles remove
// or run
toggleVisibility('your-class-name-here'); // toggles hide
Answer provided in ES6 syntax but easily can be converted to ES5 if you wish
Try :
function showClass(a){
var e = [];
var e = getElementsByClassName(a);
for(i in e ){
if(!e[i])return true;
if(e[i].style.display=="none"){
e[i].style.display="block"
} else {
e[i].style.display="none"
}
}
return true;
}
demo : showClass("float_form");

How to disable the hyperlinks in a div

How can I disable all hyperlinks in a div element? I don't want any active links in my div(editable).
jQuery:
$("#myEditableDiv a").click(function(e){ e.preventDefault(); });
Old and considered bad.
$("#myEditableDiv a").click(function(){ return false; });
using javascript you can write a simple method as given below -
function disableLinksByElement(el) {
if (document.getElementById && document.getElementsByTagName) {
if (typeof(el) == 'string') {
el = document.getElementById(el);
}
var anchors = el.getElementsByTagName('a');
for (var i=0, end=anchors.length; i<end; i++) {
anchors[i].onclick = function() {
return false;
};
}
}
}
//Call to function as
disableLinksByElement('mydiv');
First grab all the links.
var links = editable.getElementsByTagName('a'); // where "editable" is a var pointing to your div
Then set the onclick to false.
for (var i = 0; i < links.length; i++) {
var link = links[i];
link.onclick = function() { return false; };
}

Categories