Convert all 'display: none' to display block in HTML - javascript

I have an HTML web page wherein I need to find out all the elements having the display:none and style them to display:block using a script, which I can write in console or using Firebug.
There is already a script present for showing all the hidden elements in form tags. I need a similar script for display:none to display:block.
var snapHidden = document.evaluate("//input[#type='hidden']",
document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = snapHidden.snapshotLength - 1; i >= 0; i--) {
var elmHidden = snapHidden.snapshotItem(i);
elmHidden.style.MozOutline = '1px dashed #666';
elmHidden.type = 'text';
elmHidden.title = 'Hidden field "' +
(elmHidden.name || elmHidden.id) + '"';
}

Try
$('*').filter(function(){
return $(this).css('display') == 'none';
}).css('display', 'block')

$('body').find(':hidden').each(function(){
$(this).show();
});
Hope this helps.
Thanks

Here's a working solution. The first function in the javascript is taken from this stackoverflow page: jquery-check-if-element-has-a-specific-style-property
HTML:
<div id="list1">a_1</div>
<div id="list2">a_2</div>
<div id="list3" style="display:none;">a_3</div>
<div id="list4">b_1</div>
<div id="list5">b_2</div>
<div id="list6" style="display:none;">b_3</div>
<div id="list7">c_1</div>
<div id="list8" style="display:none;">c_2</div>
<div id="list9" style="display:none;">c_3</div>
JAVASCRIPT:
(function ($) {
$.fn.inlineStyle = function (prop) {
var styles = this.attr("style"),
value;
styles && styles.split(";").forEach(function (e) {
var style = e.split(":");
if ($.trim(style[0]) === prop) {
value = style[1];
}
});
return value;
};
}(jQuery));
$(document).ready( function() {
$('*:hidden').each(function(){
var display_prop = $(this).inlineStyle("display");
if(display_prop){
$(this).show();
}
});
});
FIDDLE: http://jsfiddle/d1oae3cL/1/

Related

Use AOS.js with class instead of data attribute

I want to use AOS.js on my site but I have no option to add the necessary data attributes to the DIVs of the page.
Here's the markup from the docs (https://michalsnik.github.io/aos/):
<div data-aos="fade-up" data-aos-duration="3000">
...
</div>
My markup looks like this:
<div class="aos-fade-up aos-duration-3000">
...
</div>
Is there any way to use AOS.js with only classes?
I found a similar question while researching: Having trouble adding aos.js using classes
But there is no answer to that.
Here's the code from the other question but that doesn't work:
$('.aos-fade-up').each(function(i) {
$(this).attr('data-aos', 'fade-up');
});
Any ideas?
You can give this snippet a try :
<script>
function ismatch(str){
var ret = null;
var tab = ['data-aos_', 'data-aos-delay_', 'data-aos-duration_', 'data-aos-easing_'];
Object.values(tab).forEach( function (value) {
if (String(str).match(value)){
ret = str.split('_');
return false;
}
});
return ret;
}
jQuery(document).ready(function ($) {
$('.some-class').each(function () {
var $this = $(this);
var tab = $this.attr('class').split(' ');
var keep;
Object.values(tab).forEach(function (item) {
var ello = ismatch(item)
if (ello !== null)
$this.attr(ello[0], ello[1]);
});
});
AOS.init();
});
</script>
Usage :
<div class="some-class data-aos_fade-down data-aos-delay_100 data-aos-duration_800"></div>```

Stop incremental counter and disable interaction

I am trying to get the counter to stop at 0 and when it does the entire div is unclickable/disable interaction.
There is a link in the middle. So when i click 3 times I want it to be un-clickable.
edit:also it doesn't need to use Knockout. any approach, if more simple is fine.
What would be the best approach?
Fiddle
var ClickCounterViewModel = function() {
this.numberOfClicks = ko.observable(3);
this.registerClick = function() {
this.numberOfClicks(this.numberOfClicks() - 1);
};
this.hasClickedTooManyTimes = ko.computed(function() {
return this.numberOfClicks() <= 0;
}, this);
};
ko.applyBindings(new ClickCounterViewModel());
Simply try adding this line
if (this.numberOfClicks() > 0)
Before
this.numberOfClicks(this.numberOfClicks() - 1);
We'll get something like that:
var ClickCounterViewModel = function() {
this.numberOfClicks = ko.observable(3);
this.registerClick = function() {
if (this.numberOfClicks() > 0)
this.numberOfClicks(this.numberOfClicks() - 1);
};
this.hasClickedTooManyTimes = ko.computed(function() {
return this.numberOfClicks() <= 0;
}, this);
};
ko.applyBindings(new ClickCounterViewModel());
See Fiddle
A bit late but give a look to my solution because I simplified a lot your code and I think you can get some value from it (for example the use of var self = this which is a best practice).
The idea behind my solution is very simple:
1) Show or hide the link or a normal text with respect to your hasClickedTooManyTimes computed variable.
empty link
<p data-bind='if: hasClickedTooManyTimes'>empty link</p>
2) Simply block the click on div if hasClickedTooManyTimes is true.
self.registerClick = function() {
if(!self.hasClickedTooManyTimes()){
self.numberOfClicks(this.numberOfClicks() - 1);
}
};
Check the Fiddle!
Let me know if this was useful to you!
Just disable the link when your count is done:
First add an id to your link:
<a id="a1" href=#> <p>empty link</p> </a>
Next disable that id when the time is right like this in your javascript:
this.hasClickedTooManyTimes = ko.computed(function() {
if (this.numberOfClicks() < 0) {
$('#a1').attr('disabled', 'disabled'); // <--- disable it
}
return this.numberOfClicks() <= 0;
}, this);
Take a look at the fiddle for JS code, stackoverflow is not validating my code section for the JS content.
HTML
<body>
<div>You have teste clicks!</div>
<div id="demo"></div>
</body>
JS
var btnObserver = (function() {
var me= this;
var clickleft = 3;
var registerClick = function() {
if(clickleft > 0) {
clickleft--;
}
};
var isCLickable = function() {
console.log(clickleft);
return clickleft !== 0;
};
return {
registerClick: registerClick,
isCLickable: isCLickable
}
})();
document.getElementById("mybtn").addEventListener("click", function(){
var message= "Hello World";
btnObserver.registerClick();
if(!btnObserver.isCLickable()) {
message= "X Blocked!";
// return false or do anything you need here
}
document.getElementById("demo").innerHTML = message;
});
Fiddle: http://jsfiddle.net/qkafjmdp/

getElementsByTagName('img').length logs out to 0

I have read multiple posts on this, but still don't understand why document.getElemenstsByTagName('img').length prints out '0' but when you console log it shows you the right length.
To further explain my problem, part of my HTML looks like this
<div id="parent">
<div id="slider">
</div>
</div>
Now i am dynamically adding the elements as children to the #slider element.
In my javascript i have an object
var manualSlide = {
imageLength: document.getElementsByTagName('img').length,
//other properties
};
Why does the property 'imageLength' gets assigned '0' instead of the actual length?
Edit:
Here is my entire script
<script>
$.getJSON('data.json',function(data){
$.each(data.images, function(key){
setImages(data.images[key]);
});
});
function setImages(obj){
var imgTag = '';
imgTag += "<img src='" + obj.Url + "' style='width:800px;height:400px' alt ='"+ obj.Title +"' name='pics'/>";
$('#slider').append(imgTag);
}
$(document).ready(function(){
var slide = getManualSlide();
document.getElementsByClassName('left').onclick = function(){
slide.previousImg();
};
document.getElementsByClassName('right')[0].onclick = function(){
slide.nextImg();
};
function getManualSlide(){
var manualSlide = {
imageNum : 1,
imageLength: document.getElementsByTagName('img').length,
image: document.getElementsByTagName('img'),
previousImg: function(){
if(this.imageNum > 1){
this.imageNum --;
}
else{
this.imageNum = this.imageLength;
}
document.pics.src = this.image[this.imageLength - 1];
},
nextImg: function(){
if(this.imageNum > this.imageNum){
this.imageNum ++;
}
else{
this.imageNum = 1;
}
console.log(document.getElementsByTagName('img').length);
console.log(this.imageLength);
document.pics.src = this.image[this.imageLength - 1];
}
};
return manualSlide;
}
});
</script>
It's all about where or when your code gets executed.
You have to make sure your code gets executed after the image tags are parsed (added to the DOM tree).
To do that you could put your code either behind the img-tags in the body or you wait for the document to be loaded:
<script>
document.addEventListener("DOMContentLoaded", function(event) {
imageLength = document.getElementsByTagName('img').length;
console.log(imageLength);
});
</script>
You can read more about this event here.
If you are using jQuery you could also use
$(document).ready(function(){ /* your code goes here */ });
which does exactly the same.
Because the object was created when no img tags were in the document. The object data will not update with the document. If you want this behavior you should use events.
Instead create a function to return an updated object. See below:
function getManualSlide()
{
var imgLen = document.getElementsByTagName('img').length;
var manualSlide = {
imageLength: imgLen
};
return manualSlide;
}
http://jsfiddle.net/2akca0dg/2/

Remove image from page if it already exists

I got multiple images in different divs but sometimes 2 images are exactly the same.
How do I remove all except one of those images from the page?
Is this possible with jquery/javascript? Or even css?
Example:
<div id="Content">
<div class="Media">
<img src="1.jpg">
</div>
</div>
<div id="Content">
<div class="Media">
<img src="2.jpg">
</div>
</div>
<div id="Content">
<div class="Media">
<img src="1.jpg">
</div>
</div>
<div id="Content">
<div class="Media">
<img src="4.jpg">
</div>
</div>
<div id="Content">
<div class="Media">
<img src="1.jpg">
</div>
</div>
How do I make it so it only shows one of the divs with:
<img src="1.jpg">
This is the server side code It returns a big json file with all the posts from the twitter page but i didnt think it was possible to filter it so it checks for duplicates first?
success: function(data){
twitter = JSON.parse(data);
for(var key in twitter.statuses){
if (typeof twitter.statuses[key].entities.media != "undefined") {
if( $.inArray(twitter.statuses[key].entities.media, container) == -1 ) {
container.push(twitter.statuses[key]);
}
}
}
},
error: function(data){
console.log(data);
}
I hope someone knows how to solve this problem Thanks!
You can get all the IMG tags and see if the src is unique. If it isn't, you can remove it. Here is an example:
$(document).ready(function() {
var img = $("img");
var used = {};
img.each(function() {
var src = $(this).attr('src');
if(used[src]) $(this).remove();
used[src]=1;
});
})
CodePen here: http://codepen.io/cfjedimaster/pen/tDprC
I'm using the filter function from jQuery.
First, I'm selecting all image child elements from the 'Media' class. After that, I'm using the filter function to reduce the set of matched elements to those, which aren't in my array. Then I'm deleting them. (Including the parent node)
I'm not sure whether this is the ideal solution, but you can give it a try.
$(function() {
var $allImages = $( '.Media > img' ),
tmp,
allUsedImageSrcs = [];
$allImages.filter( function() {
tmp = $( this ).attr( 'src' );
if( $.inArray( tmp, allUsedImageSrcs ) < 0 ) {
allUsedImageSrcs.push( tmp );
return false;
}
return true;
}).closest( '#Content' ).remove();});
Here's a fiddle of my implementation with jQuery, although you could achieve the same functionality without jQuery.
http://jsfiddle.net/6jb3hoc9/1/
with javascript you could do it like that (pseudo) idea
$('#content.media img'){
//fill the array with src
//check if array item is same
//remove item
var array;//array of src tag
foreach(item in array as value)
if(value['src'] == value['src'])
{
arr.remove();
//remove item from dom **
}
}
How to remove item from DOM http://www.w3schools.com/js/js_htmldom_nodes.asp
Kind of don't know what you want.
Suppose you want to remove img element with the duplicated src.
// Retrieve all the images
var imgs = document.querySelectorAll(".Media > img");
// To memorize srcs appear before
var srcExisted = [];
for (var i = imgs.length - 1; i >= 0; i--) {
if (srcExisted.indexOf(imgs[i].src) < 0) {
// The 1st appearing, memorize
srcExisted.push(imgs[i].src);
} else {
// Already existed, remove
imgs[i].parentNode.removeChild(imgs[i]);
imgs[i] = null;
}
}
I have write this function for you.
window.addEventListener("load", function () {
var images = Array.prototype.slice.call(document.getElementsByTagName('img'));
if (images.length == 0) {
return;
}
(function handleImages(imgHash) {
var process = function (image) {
if (typeof imgHash[image.src] == 'undefined') {
imgHash[image.src] = true;
} else {
image.parentNode.removeChild(image);
}
};
setTimeout(function () {
process(images.shift());
if (images.length > 0) {
setTimeout(function () {
handleImages(imgHash);
}, 0);
}
}, 0);
})({});
}, false);
About your other problem. You must rewrite logic into success to be asynchronous.
Check this:
success: function(data){
var twitter = JSON.parse(data);
var props = Object.getOwnPropertyNames(twitter.statuses);
var result = [];
var dfd = $.Deferred();
if (props.length == 0) {
return;
}
(function handleProps(propsHash) {
var process = function (prop) {
if (typeof twitter.statuses[prop].entities.media != "undefined" && typeof propsHash[twitter.statuses[prop].entities.media] == 'undefined') {
result.push(twitter.statuses[prop]);
propsHash[twitter.statuses[prop].entities.media] = true;
}
};
setTimeout(function () {
process(props.shift());
if (props.length > 0) {
setTimeout(function () {
handleProps(propsHash);
}, 0);
} else {
dfd.resolve(result);
}
}, 0);
})({});
dfd.done(function(result) {
console.log(result);
});
}
Instead console.log(result); you must call other code that will
handle result.

Add multiple items to text-area with duplicate items

Add multiple items to text-area with duplicate items.
I have one text-area which store data after clicked add data link.
How can i prevent add duplicate items to text-area?
JavaScript call DOM event:
var Dom = {
get: function(el) {
if (typeof el === 'string') {
return document.getElementById(el);
} else {
return el;
}
},
add: function(el, dest) {
var el = this.get(el);
var dest = this.get(dest);
dest.appendChild(el);
},
remove: function(el) {
var el = this.get(el);
el.parentNode.removeChild(el);
}
};
var Event = {
add: function() {
if (window.addEventListener) {
return function(el, type, fn) {
Dom.get(el).addEventListener(type, fn, false);
};
} else if (window.attachEvent) {
return function(el, type, fn) {
var f = function() {
fn.call(Dom.get(el), window.event);
};
Dom.get(el).attachEvent('on' + type, f);
};
}
}()
};
JQuery add data to textarea:
$("#lkaddlanguage").click(function(){
var totalstring;
var checkconstring = $("#contentlng").text();
var strLen = checkconstring.length;
myStr = checkconstring.slice(0,strLen-1);
//alert(myStr);
var checkedItemsArray = myStr.split(";");
var j = 0;
var checkdup=0;
totalstring=escape($("#textval").val()) ;
var i = 0;
var el = document.createElement('b');
el.innerHTML = totalstring +";";
Dom.add(el, 'txtdisplayval');
Event.add(el, 'click', function(e) {
Dom.remove(this);
});
});
HTML Display data
<input type="textbox" id="textval">
<a href="#lnk" id="lkaddlanguage" >Add Data</a>
<textarea readonly id="txtdisplayval" ></textarea>
This seems a very straightforward requirement to me, so I'm not quite clear where you're getting stuck. I have not tried too hard to figure out your existing code given that you are referencing elements not shown in your html ("contentlng"). Also, mixing your own DOM code with jQuery seems a bit pointless. You don't need jQuery at all, but having chosen to include it why then deliberate not use it?
Anyway, the following short function will keep a list of current items (using a JS object) and check each new item against that list. Double-clicking an item will remove it. I've put this in a document ready, but you can manage that as you see fit:
<script>
$(document).ready(function() {
var items = {};
$("#lkaddlanguage").click(function(){
var currentItem = $("#textval").val();
if (currentItem === "") {
alert("Please enter a value.");
} else if (items[currentItem]) {
alert("Value already exists.");
} else {
items[currentItem] = true;
$("#txtdisplayval").append("<span>" + currentItem + "; </span>");
}
// optionally set up for entry of next value:
$("#textval").val("").focus();
return false;
});
$("#txtdisplayval").on("dblclick", "span", function() {
delete items[this.innerHTML.split(";")[0]];
$(this).remove();
});
});
</script>
<input type="textbox" id="textval">
<a href="#lnk" id="lkaddlanguage" >Add Data</a><br>
<div id="txtdisplayval" ></div>
<style>
#txtdisplayval {
margin-top: 5px;
width : 200px;
height : 100px;
overflow-y : auto;
border : 1px solid black;
}
</style>
Note I'm using a div (styled to have a border and allow vertical scrolling) instead of a textarea.
As you can see I've coded it to display an alert for duplicate or empty items, but obviously you could remove that and just ignore duplicates (or substitute your own error handling). Also I thought it might be handy to clear the entry field and set focus back to it ready for entry of the next value, but of course you can remove that too.
Working demo: http://jsfiddle.net/LTsBR/1/
I'm confused.
The only variable that might have duplicates comes from:
var checkedItemsArray = myStr.split(";");
However, checkedItemsArray is not used for anything.
Incidentally, the escape method is deprecated in favour of encodeURIComopnent.
When setting the value of the textarea, do just that: assign to its value property, not to its innerHTML (it can't have markup inside it or any elements, only text nodes).
If you want to check that the members of checkedItemsArray are unique, and you don't mind if they are sorted, you can use a simple function like:
function unique(arr) {
arr.sort();
var i = arr.length;
while (i--) {
if (arr[i] == arr[i - 1]) {
arr.splice(i, 1);
}
}
return arr;
}
Orignal order can be maintained, but it's a bit more code.

Categories

Resources