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.
Related
The goal: check if all images in the page are loaded. If yes, call to a function, if not, again to check if all images are loaded.
My try:
let checkImages = new Promise(resolve => { resolve(areCompleted()); });
function areCompleted() {
let images = document.querySelectorAll('img');
images = Array.from(images);
for (let i = 0; i < images.length; i++) {
if (!images[i].complete) {
return false;
}
}
return true;
}
If all images are completed, it resolves the promise with true, if not, false.
checkImages.then(completed => {
if (completed) {
completedFunction();
} else {
// Check again
}
});
If the response is true, call a function, if not... I don't know how to do the same check again, but I want to do that checking until the response is true.
This function will check for already loaded images and attach an event listener to all the others so that it can tell when every image in a given container is loaded...
function onImagesLoaded(container, event) {
var images = container.getElementsByTagName("img");
var loaded = images.length;
for (var i = 0; i < images.length; i++) {
if (images[i].complete) {
loaded--;
}
else {
images[i].addEventListener("load", function() {
loaded--;
if (loaded == 0) {
event();
}
});
}
if (loaded == 0) {
event();
}
}
}
var container = document.getElementById("container");
onImagesLoaded(container, function() {
alert("All the images have loaded");
});
<div id="container">
<img src="https://cdn.vox-cdn.com/thumbor/C1SdoDActSv8tPONx_OjwEobUjw=/0x0:1004x753/1200x800/filters:focal(0x0:1004x753)/cdn.vox-cdn.com/uploads/chorus_image/image/49523369/20150428-cloud-computing.0.jpg" />
<img src="https://images.techhive.com/images/article/2016/08/clouds-100678070-primary.idge.jpg" />
<img src="https://www.quali.com/wp-content/uploads/2016/04/101-HEADER-IMAGE.jpg" />
<img src="https://cdn.computerworlduk.com/cmsdata/features/3641280/cloud_istock_malerapaso_thumb800.jpg" />
</div>
This will still work if all the images have already loaded, due to being cached, or if there are no images in the container.
If you want to check all images in a page, simply change the container selector to the body instead...
var container = document.getElementsByTagName("body")[0];
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/
I currently have the following code on my website:
$(document).ready(function() {
$("#contact").on("click", function(e)
{
e.preventDefault();
$("#contactform").toggle('fast');
});
});
I would like to have an if(isset($_GET['email')); trigger this function as well, so have it open on page load if the $_GET variable is set.
I'm rather new with Jquery and not sure if this is possible, I also have another somewhat related question, I'm not sure if I should make a new question for this as I'm fairly new to stackoverflow as well, but here it is.
Say I have two of these:
$(document).ready(function() {
$("#contact").on("click", function(e)
{
e.preventDefault();
$("#contactform").toggle('fast');
});
});
$(document).ready(function() {
$("#archivestop").on("click", function(e)
{
e.preventDefault();
$("#archives").toggle('fast');
});
});
I want one to close if the other one is opened, how would I go about this?
Thanks!
Here's the Javascript-solution:
function getParam(key) {
var paramsStr = window.location.search.substr(1, window.location.search.length),
paramsArr = paramsStr.split("&"),
items = [];
for (var i = 0; i < paramsArr.length; i++) {
items[paramsArr[i].split("=")[0]] = paramsArr[i].split("=")[1];
}
if (key != "" && key != undefined) {
// return single
if (items[key] != undefined) {
return items[key];
} else {
return null;
}
} else {
// return all (array)
return items;
}
};
if (getParam("email")) {
// ...
}
Regarding your second question you can use the following to determine if an element is visible:
var bool = $('.foo').is(":visible");
So to hide an element if it is visible you would do something like this:
if ($('.foo').is(":visible")) {
$('.foo').hide();
}
I'm silly and have answered my first question. I still have yet to have my coffee.
The following works, just insert it into the div that is to be displayed:
<div id="contactform" style="<?php if(isset($_POST['email'])) echo "display:block;" ?>">
content
</div>
The headline says it all. At start of my app I retrieve data from a php file (some divs) and append them to an wrapper-div. Around this wrapper-div (not called wrapper) is the iScroll wrapper.
iScroll is working, but there is a rubberband effect.
Here's the (index) HTML:
<div data-role="header" data-theme="c" data-position="fixed">
<h1>Title</h1>
</div><!-- /header -->
<div id="wrapper">
<div id="scroller">
<div data-role="content" id="content">
<div id="headlinesindex">
<div class="span3" id="9999999999"></div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
onBodyLoad();
});
</script>
And here's the javascript-file:
function onBodyLoad()
{
$.ajax({
url: "headlines_getter.php?last="+ $(".span3:last").attr('id') ,
success: function(html) {
if(html){
$("#headlinesindex").append(html);
setTimeout(function () {
myScroll.refresh();
}, 0);
}
}
});
}
function onDeviceReady()
{
var myScroll = new iScroll('wrapper');
}
I've played arround with the setTimeout as it is explained at iscroll.com, but it changes nothing... Hope you know what's wrong.
Thanks in advance. Best regards, John.
I had the same issue.
It came from the outer "wrapper" not being sized correctly in iscroll.
If it is sized the same size as the inner "scroller" height then the iscroll will have no where to go and rubber band.
I fixed it for me, and created a fork for others with the same issue:
https://github.com/meckdahl/iscroll
================================== Advanced Usage
Here is some addon functions I use to maintain my 20+ scroll containers in our Spine.JS mobile app:
For each page I set a specific wrapper like such:
<div id="wrapper2">
Then I dynamically create iScroll only if that page is loaded:
After the content for the page is loaded I call like such:
window.resetScroll(2)
window.setScrolling(true)
This will re-initialize iScroll for this page.
Here are the functions I define on my root page:
<script type="text/javascript">
// maximum wrapper index = 23 currently (9/12/12)
var myScrolls = [];
myScrolls.length = 29; // Scrolls to look for wrapper1-30
var refreshScrolling = function() {
//console.log('refreshScrolling Active Scroll Items: ');
myScrolls.forEach( function(scrollItem){
scrollItem.refresh();
});
};
var refreshScroll = function(wrapperNumber) {
//console.log('refreshScroll wrapperNumber: wrapper' + wrapperNumber.toString());
var i = wrapperNumber;
setTimeout(function () {
(myScrolls[i-1]).refresh();
}, 100);
};
// This looks for and initializes and dynamic scrolls that Spine recently put in memory
// and have not been initialized yet.
var setScrolling = function() {
for (var i=1; i < myScrolls.length+1; i++){
if (($("#wrapper"+(i).toString()).length !== 0) ){
if((myScrolls[i-1] !== null) && (myScrolls[i-1] !== undefined)){
// Already setup
}
else{
myScrolls[i-1] = new iScroll('wrapper'+ (i).toString(),
{ hScroll: false, hScrollbar: false, vScrollbar: false });
created.");
}
}
}
}
// This must be called on a view with dynamic content to re-create the view to fit the potentially
// changing content size. It will only rebuild the one scroll whose index is passed in.
// The index should be the wrapper# for the view attached to the controller.
// Call setScrolling after this to catch any uninitialized views.
var resetScroll = function(wrapperNumber) {
var i = wrapperNumber;
// if (!(i in myScrolls)) continue; // skip nonexistent elements && !(myScrolls[i-1] )
if (($("#wrapper"+(i).toString()).length !== 0) ){
if( (myScrolls[i-1] !== null) && (myScrolls[i-1] !== undefined)){
// Destroy Skipped right now
myScrolls[i-1].destroy();
myScrolls[i-1] = null;
}
myScrolls[i-1] = new iScroll('wrapper'+ (i).toString(),
{ hScroll: false, hScrollbar: false, vScrollbar: false });
created.");
}
}
function loaded() {
setTimeout(function () {
setScrolling();
}, 100);
}
window.addEventListener('load', loaded, false);
</script>
I had the same problem with my custom script so I changed the code and now it's working nicely:
var myScroll;
function loaded() {
setTimeout(function(){
myScroll = new iScroll('wrapper');
myScroll.refresh();
} , 100 );
}
And I call it on "onDeviceReady":
function onDeviceReady()
{
loaded();
}
http://jsfiddle.net/Eccgy/
Check this may be help you
Here is a simple iscroller that would help .
its very easy to implement
include scripts and jsut add an attribute data-iscroll to the div, which you need the effect.
https://github.com/watusi/jquery-mobile-iscrollview
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.