How to remove all element except one? - javascript

I would like to remove all element from my canva except the one on which I click.
I create a set, put all element inside and remove the set :
button.click(function () {
var to_remove = paper.set();
paper.forEach(function (el) {
to_remove.push(el);
});
to_remove.remove();
});
But i don't success to test if my element is my button or not.
Axel

You can simply cache your clicked element and compare it during the loop.
button.click(function() {
var clickedEl = this,
toRemove = paper.set();
paper.forEach(function(el) {
if (el !== clickedEl) {
toRemove.push(el);
}
});
toRemove.remove();
});​
Demo: http://jsfiddle.net/yRNNe/

Related

how to exchange the attribute values simultaneously on single click event using jQuery

I want to replace #cardvieo_localstream with #cardvideo_remotestream at the first click, again I click the same element, I want to change #cardvideo_remotestream back #cardvieo_localstream, I'm not sharp at jQuery yet, but I'm trying to learn. I appreciate all help I can get.
I've try this code but working on first click. but not working on second click
$('.video-list .videoWrap').on('click', function() {
var $thisVideoWrap = $(this).find('.video-list .videoWrap');
var $mainVideoWrap = $('.mainVideoWrap');
if ($(this).attr('id') === '#cardvideo_localStream') {
$(this).attr('id', '#cardvideo_remotestream');
}
else if($(this).attr('id') == '#cardvideo_localStream') {
$(this).attr('id', '#cardvideo_local');
$mainVideoWrap.attr('id', 'cardvideo_remotestream');
}
});
Don't change An Id Attribute because of id is a unique value Only use the Classname, I swap the elements successfully
// using jQuery
var initVideoSwapping = function () {
// check if there is an element first
if ($('.video-list .videoWrap').length > 0) {
$('.video-list .videoWrap').on('click', function () {
var $thisVideo = $(this).find('video')[0];
var $mainVideo = $('.mainVideoWrap').find('video')[0];
swapNodes($thisVideo, $mainVideo)
});
}
}
function swapNodes(a, b) {
var aparent = a.parentNode;
var asibling = a.nextSibling === b ? a : a.nextSibling;
b.parentNode.insertBefore(a, b);
aparent.insertBefore(b, asibling);
}
$(function () {
initVideoSwapping();
});

How to combine multiple onclick events/elements

I have this toggle function which has multiple buttons.
var button1 = document.querySelector('#button1');
var button2 = document.querySelector('#button2');
var button3 = document.querySelector('#button3');
var toggleState = function (elem, one, two) {
var elem = document.querySelector(elem);
elem.setAttribute('data-state', elem.getAttribute('data-state') === one ? two : one); //ternary operator
};
button1.onclick = function (e) {
toggleState('#div1', 'open', 'closed');
e.preventDefault();
};
button2.onclick = function (e) {
toggleState('#div2', 'open', 'closed');
e.preventDefault();
};
button3.onclick = function (e) {
toggleState('#div3', 'open', 'closed');
e.preventDefault();
};
I've tried querySelectorAll to combine variables but it doesn't work. I think I know why. But I can't figure out a way to write the script more eloquently. (scratch eloquently. respectable is a better word)
How can I combine variables and onclicks so that the code is not so redundant?
Here is one solution:
You need to get button elements and trigger an onclick event for them.
Instead of trigger onclick event handler per each button, you could use a loop.
Read more about bind function
var buttons=document.getElementsByTagName('button');
var toggleState = function (elem, one, two) {
var elem = document.querySelector(elem);
elem.setAttribute('data-state', elem.getAttribute('data-state') === one ? two : one); //ternary operator
};
for(var i=0;i<buttons.length;i++){
var button=document.querySelector('#button'+(i+1));
button.onclick=(function(index){;
toggleState('#div'+index,'open','closed');
}).bind(this,i+1);
}
Consider a solution similar to the one below. Instead of copying the event handler per element, you could process each of the elements in a loop.
If the element ids are consistent, you could make it even briefer by only specifying the number of toggles and generating the ids on the fly.
var toggles = {
'#button1': '#div1',
'#button2': '#div2',
'#button3': '#div3'
};
Object.keys(toggles).forEach(function(toggle) {
document.querySelector(toggle).onclick = function (e) {
toggleState(toggles[toggle], 'open', 'closed');
e.preventDefault();
};
});
function toggleState(elem, one, two) {
var elem = document.querySelector(elem);
elem.setAttribute('data-state', elem.getAttribute('data-state') === one ? two : one);
};

Get Bouncy Content Filter to run automatically

I'm using this awesome bouncy filter from Codyhouse but i can't for the life of me figure out how to make it run automatically i.e flip on its own and still accept user click events. The jsfiddle...Thanks.
jQuery(document).ready(function($) {
//wrap each one of your filter in a .cd-gallery-container
bouncy_filter($('.cd-gallery-container'));
function bouncy_filter($container) {
$container.each(function() {
var $this = $(this);
var filter_list_container = $this.children('.cd-filter'),
filter_values = filter_list_container.find('li:not(.placeholder) a'),
filter_list_placeholder = filter_list_container.find('.placeholder a'),
filter_list_placeholder_text = filter_list_placeholder.text(),
filter_list_placeholder_default_value = 'Select',
gallery_item_wrapper = $this.children('.cd-gallery').find('.cd-item-wrapper');
//store gallery items
var gallery_elements = {};
filter_values.each(function() {
var filter_type = $(this).data('type');
gallery_elements[filter_type] = gallery_item_wrapper.find('li[data-type="' + filter_type + '"]');
});
//detect click event
filter_list_container.on('click', function(event) {
event.preventDefault();
//detect which filter item was selected
var selected_filter = $(event.target).data('type');
//check if user has clicked the placeholder item (for mobile version)
if ($(event.target).is(filter_list_placeholder) || $(event.target).is(filter_list_container)) {
(filter_list_placeholder_default_value == filter_list_placeholder.text()) ? filter_list_placeholder.text(filter_list_placeholder_text): filter_list_placeholder.text(filter_list_placeholder_default_value);
filter_list_container.toggleClass('is-open');
//check if user has clicked a filter already selected
} else if (filter_list_placeholder.data('type') == selected_filter) {
filter_list_placeholder.text($(event.target).text());
filter_list_container.removeClass('is-open');
} else {
//close the dropdown (mobile version) and change placeholder text/data-type value
filter_list_container.removeClass('is-open');
filter_list_placeholder.text($(event.target).text()).data('type', selected_filter);
filter_list_placeholder_text = $(event.target).text();
//add class selected to the selected filter item
filter_values.removeClass('selected');
$(event.target).addClass('selected');
//give higher z-index to the gallery items selected by the filter
show_selected_items(gallery_elements[selected_filter]);
//rotate each item-wrapper of the gallery
//at the end of the animation hide the not-selected items in the gallery amd rotate back the item-wrappers
// fallback added for IE9
var is_explorer_9 = navigator.userAgent.indexOf('MSIE 9') > -1;
if (is_explorer_9) {
hide_not_selected_items(gallery_elements, selected_filter);
gallery_item_wrapper.removeClass('is-switched');
} else {
gallery_item_wrapper.addClass('is-switched').eq(0).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() {
hide_not_selected_items(gallery_elements, selected_filter);
gallery_item_wrapper.removeClass('is-switched');
});
}
}
});
});
}
});
function show_selected_items(selected_elements) {
selected_elements.addClass('is-selected');
}
function hide_not_selected_items(gallery_containers, filter) {
$.each(gallery_containers, function(key, value) {
if (key != filter) {
$(this).removeClass('is-visible is-selected').addClass('is-hidden');
} else {
$(this).addClass('is-visible').removeClass('is-hidden is-selected');
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm assuming by "make it run automatically" you're talking about triggering the content-selection animation programatically, rather than requiring a user click. One possible solution is to assign an id to the selection elements, and then register the click handler directly to those elements, rather than the parent filter_list_container. Then, you can use jQuery's trigger() method to simulate a click on the appropriate element.
Assign an id in the html like this:
<a id="green" href="#0">Green</a>
Then register the click handler like this:
$("#red, #green, #blue").on('click', function(event){ ... }
...and trigger like this:
$("#green").trigger("click");
Here's a JSfiddle with an example.

Checkbox unclick event Javascript

I have problem that checkbox uncheck event. When I unclick the checkbox it should be revert back. How can I do this?
<body>
<script>
function change()
{
var cb = document.querySelectorAll('input[type="checkbox"]')[0];
var td = document.querySelectorAll("td[contenteditable]")[0];
cb.addEventListener("click", function () {
td.className = td.className + " crossed";
});
}
</script>
</body>
Either toggle the class like:
cb.addEventListener("click", function () {
td.classList.toggle("crossed");
});
JSFiddle Demo
Or check if the checkbox is checked:
cb.addEventListener("click", function () {
if(cb.checked) td.classList.add("crossed");
else td.classList.remove("crossed");
});
JSFiddle Demo
If you want to keep the older browser support, you can do it like:
cb.addEventListener("click", function() {
if (cb.checked) td.className += " crossed";
else {
var tdclass = td.className.split(" "),
ind = tdclass.indexOf("crossed");
tdclass.splice(ind, 1).join(" ");
td.className = tdclass;
}
});
JSFiddle Demo
While you've already accepted an answer, I'd suggest a minor adjustment to the following:
function change() {
// querySelector() returns the first element matching the
// selector (or null, if no matching element is found):
var cb = document.querySelector('input[type="checkbox"]'),
td = document.querySelector("td[contenteditable]");
// use the change event on the check-box:
cb.addEventListener("change", function () {
// adds, or removes, the class 'crossed'
// based on the assessment that follows;
// of the cb node is checked (true) the
// class is added (if not already present),
// otherwise it's removed:
td.classList.toggle('crossed', cb.checked);
});
}
okay u want a tick to be re-enable when u click on it to unclick!!!
$("input[type='checkbox']").props('checked','false') {
$("input[type='checkbox']").props('checked','true')
}
Try to use a selector like id or something in place of: input[type='checkbox']

Create element from input type='text' JavaScript

I want to create DOM elements with info taken from input type text. To be more specific:
I want the user to be able to write a location and after he presses "Go!" button an element to be created with the text inserted and I also want to have a delete icon which when pressed to delete that insert.
I created a function in which I took the input value but I cannot create the 'del' button
If I create another <img> inside using the same method, when I create the second entry it will put another <img> to the previous entry
search_btn.click(function() {
var place_reg = /^[a-z]+\d*[a-z]*(\s[a-z]+\d*[a-z]*)*?$/i;
var search_value = search_box.val();
var final_result = search_value.trim();
if (place_reg.test(final_result)) {
createDest(final_result);
} else {
alert('Please insert a valid destination');
}
document.getElementById('search_box').value = "";
});
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){ return txt.charAt(0).toUpperCase() +
txt.substr(1).toLowerCase();});
}
function createDest(value) {
var destination_i_search = document.createElement("div");
destination_i_search.innerHTML = toTitleCase(value);
destination_i_search.setAttribute("class" , "place");
$("#dest").append(destination_i_search);
}
It is very difficult to understand what you wish it to do, without a full example, but from comments you may want something like this:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/s6hn0n18/6/
I have converted it to use jQuery where appropriate.
var search_btn = $('#search');
var search_box = $('#searchbox');
search_btn.click(function () {
var place_reg = /^[a-z]+\d*[a-z]*(\s[a-z]+\d*[a-z]*)*?$/i;
var search_value = search_box.val() || "";
var final_result = search_value.trim();
if (place_reg.test(final_result)) {
createDest(final_result);
} else {
alert('Please insert a valid destination');
}
search_box.val("");
});
function toTitleCase(str) {
return str.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
function createDest(value) {
// use a div container
var div = $("<div/>");
div.html(toTitleCase(value));
div.addClass("place");
// If you want to replace the previous entry
$("#dest").append(div);
var del = $('<input class="delete" type="button" value="X"/>');
$("#dest").append(del);
}
// This is a delegated event handler, attached to a non-changing ancestor
$(document).on('click', '.delete', function(){
// Remove the previous div (if of class place)
$(this).prev('.place').remove();
// Remove the delete button too
$(this).remove();
});
The key is to add a delegated event handler for the delete buttons. These work by listening for the specified event (click in this case) bubbling up to a non-changing ancestor. It the applies the jQuery selector. It the calls the function for any matching element that caused the event. The default ancestor is document if nothing closer to the changing content is available. In this case you could use #dest
e.g.
$('#dest').on('click', '.delete', function(){

Categories