I want to remove a div by userscripts where only possible thing to differ the div is bacground image in inline css.
Suppose a div has the following CSS:
(background-image:http://www.example.com/example.png)
Could anyone help me about that?
I have tried the following one but not working.
var badDivs = $("div div:contains('background-image')");
badDivs.remove ();
Use:
$("div").each(function() {
if ($(this).css("background-image") != 'none') {
$(this).remove();
}
});
Documentation: .each(), .css(), .remove().
WARNING!! checking ALL div will be a huge work, you should use a class like toCheck instead. So:
$(".toCheck").each(function() {
if ($(this).css("background-image") != 'none') {
$(this).remove();
}
});
Working DEMO.
$(".toCheck").each(function() {
if ($(this).css("background-image") != 'none') {
$(this).remove();
}
});
div {
border:1px solid #000;
}
.toCheck {
width: 100px;
height: 100px;
}
#withImage {
background-image: url("http://www.placehold.it/100/100");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="toCheck" id="withImage">
Div to check with an image
</div>
<div class="toCheck">
Div to check without an image
</div>
<div>
Normal div
</div>
UPDATE:
Since your class toCheck is partial-variable you will need a more tricky script using Regular Expression. First you need to extend JQUERY selectors (tutorial) so for :regex:
jQuery.expr[':'].regex = function(elem, index, match) {
var matchParams = match[3].split(','),
validLabels = /^(data|css):/,
attr = {
method: matchParams[0].match(validLabels) ?
matchParams[0].split(':')[0] : 'attr',
property: matchParams.shift().replace(validLabels,'')
},
regexFlags = 'ig',
regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
return regex.test(jQuery(elem)[attr.method](attr.property));
}
then use it with your variable class:
$("div:regex(class, profile_view_img_+[0-9]*)").each(function() {
if ($(this).css("background-image") != 'none') {
$(this).remove();
}
});
Updated DEMO.
jQuery.expr[':'].regex = function(elem, index, match) {
var matchParams = match[3].split(','),
validLabels = /^(data|css):/,
attr = {
method: matchParams[0].match(validLabels) ?
matchParams[0].split(':')[0] : 'attr',
property: matchParams.shift().replace(validLabels,'')
},
regexFlags = 'ig',
regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
return regex.test(jQuery(elem)[attr.method](attr.property));
}
$("div:regex(class, profile_view_img_+[0-9]*)").each(function() {
if ($(this).css("background-image") != 'none') {
$(this).remove();
}
});
div {
border:1px solid #000;
}
.toCheck {
width: 100px;
height: 100px;
}
#withImage {
background-image: url("http://www.placehold.it/100/100");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="profile_view_img_22222222" id="withImage">
Div to check with an image
</div>
<div class="profile_view_img_1111111">
Div to check without an image
</div>
<div>
Normal div
</div>
Related
My intention is to make div when keydown, and remove div when the same key is pressed again.
This is my code.
let keydown = false;
document.addEventListener('keydown', function(e) {
if (e.code === 'Space') {
if (!keydown) {
keydown = true;
console.log("space")
e.preventDefault(); //space doesn't manipulate position
$("body").append($("<div id='refactor'></div>"))
$(refactor).append($(".highlight").text())
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
What should I do to remove the div when Space is hit again?
First of all...jquery...avoid this bloatware by all means, please...
Of course this is based on what you've asked here, but I'd recommend instead of store true/false for the pressed key, store the new div element instead. This way, you'll have instant access to it without need search in the DOM.
To remove a node from the DOM, you just need execute node.removeChild(child)
let div = null;
document.addEventListener('keydown', function(e) {
if (e.code === 'Space') {
console.log("space")
e.preventDefault(); //space doesn't manipulate position
if (div)
{
//remove div from DOM
div.parentNode.removeChild(div);
div = null;
}
else
{
//create new div
div = document.createElement("div");
div.id = "refactor";
div.textContent = document.querySelector(".highlight").textContent;
document.body.appendChild(div);
}
}
})
#refactor
{
background-color: lightgreen;
}
<div class="highlight">test</div>
If your whole goal is to show/hide an element, than you should do so via CSS instead of adding/removing elements from DOM, it's significantly faster and allows add additional animations/styles:
let div = document.getElementById("refactor");
document.addEventListener('keydown', function(e) {
if (e.code === 'Space') {
console.log("space")
e.preventDefault(); //space doesn't manipulate position
if (div.classList.contains("hidden"))
{
div.textContent = document.querySelector(".highlight").textContent + " " + Date();
}
div.classList.toggle("hidden");
}
})
#refactor
{
background-color: lightgreen;
transition: height 0.5s, width 0.5s, background-color 0.5s;
height: 1.5em;
width: 100%;
overflow: hidden;
}
#refactor.hidden
{
height: 0;
width: 0;
background-color: pink;
}
<div class="highlight">test</div>
<div id="refactor" class="hidden"></div>
<div>blah</div>
Here's the script I have:
I would like to convert it to pure JavaScript, so I won't have to use jQuery.
if ( $('#movie.playing').length ) {
$('.settings').click();
$('<style> .element { display: none; } </style>').appendTo(document.head);
$('.item').click(function() {
if ($(this).text().trim() === "Ann") {
if ($(this).attr('aria-checked') == 'true') {
$('.element').css('display', 'block');
} else {
$('.element').css('display', 'none');
}
}
});
}
Here's what I have so far:
var movie = document.querySelector("#movie_player.playing-mode");
if ( movie ) {
document.querySelector(".settings").click();
var style = document.createElement("text/css");
style.styleSheet.cssText = ".element { display: none; }";
document.head.appendChild(style);
document.querySelector(".item").click(function() {
/* what do I do with this part? */
if ($(this).text().trim() === "Ann") {
if ($(this).attr('aria-checked') == 'true') {
$('.element').css('display', 'block');
} else {
$('.element').css('display', 'none');
}
}
});
}
I don't know how to convert the if-statement, where on click of the button with text "Ann" it is going to switch the elements from display: block to none and vice versa.
$(selector) = document.querySelector(selector)
$(selector).click() = document.querySelector(selector)(maybe cache the element first).addEventlistener(eventType, fn)
css stuff can be add as 'class' like el.classList.add(someClassName).
UPDATE
It's better to get the basic knowledge with JavaScript | MDN. Personal it's easy than jQuery.
I know there are lots of ways to detect the click outside of an element. Mostly all of them use event.stopPropagation. Since event.stopPropagation will break other stuff, I was wondering if there is another way to achieve the same effect. I created a simple test for this:
HTML:
<div class="click">Click me</div>
Javascript:
$(function() {
var $click = $('.click'),
$html = $('html');
$click.on( 'click', function( e ) {
$click.addClass('is-clicked').text('Click outside');
// Wait for click outside
$html.on( 'click', clickOutside );
// Is there any other way except using .stopPropagation / return false
event.stopPropagation();
});
function clickOutside( e ) {
if ( $click.has( e.target ).length === 0 ) {
$click.removeClass('is-clicked').text('Click me');
// Remove event listener
$html.off( 'click', clickOutside );
}
}
});
http://jsfiddle.net/8p4jhvqn/
This works, but only because i stop the bubbling with event.stopPropagation();. How can i get rid of event.stopPropagation(); in this case?
It can be done in a simpler way, can't it be? Why complicate things when something as simple as below could work.
$(document).click(function(e){
var elm = $('.click');
if(elm[0] == e.target){
elm.addClass("is-clicked").text("click outside");
} else { elm.removeClass("is-clicked").text("click inside"); }
});
DEMO
You could do something like this to achieve the same effect
$(document).on("click", function(e){
var target = $(e.target);
if(target.hasClass("click")){
$click.addClass('is-clicked').text('Click outside');
}else{
$click.removeClass('is-clicked').text('Click me');
}
});
HTML code:
<div id="box" style="width:100px; height:100px; border:1px solid #000000; background-color:#00ff00;"></div>
JavaScript code:
function Init()
{
$(document).click(function(event){
if(event.target.id == "box")
{
$(event.target).css("backgroundColor", "#ff0000");
}
else
{
$("#box").css("backgroundColor", "#00ff00");
}
})
}
$(document).ready(Init);
If the element in question has child elements, then those may show up as e.target, and you can't simply compare it to your element.
In that case, capture the event in both the event and in the document, and detect events which only occurred on the document, for example by recording and comparing e.target:
var lastTarget = undefined;
$("#interesting-div").click(function(e) {
// remember target
lastTarget = e.target;
});
$(document).click(function(e) {
if (e.target != lastTarget) {
// if target is different, then this event didn't come from our
// interesting div.
// do something interesting here:
console.log("We got a click outside");
}
});
var lastTarget = undefined;
$("#interesting-div").click(function(e) {
// remember target
lastTarget = e.target;
});
$(document).click(function(e) {
if (e.target != lastTarget) {
// if target is different, then this event didn't come from our
// interesting div.
// do something interesting here:
console.log("We got a click outside");
}
});
#interesting-div {
background: #ff0;
border: 1px solid black;
padding: .5em;
}
#annoying-childelement {
background: #fa0;
border: 1px solid black;
margin: 1em;
padding: .5em;
width: 20em;
}
#large-div {
background: #ccc;
padding: 2em 2em 20em 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="large-div">
<div id="interesting-div">
This is our interesting element
<div id="annoying-childelement">
child element
</div>
</div>
</div>
</div>
Couldn't find a solution that actually worked, but I want that on a click, a div shows.
Now this works when I load the page, but then after that first click, I have to click twice every time for the div to show.
Any ideas?
$(document).ready(function () {
setMenu();
});
function setMenu()
{
var headerExtIsOpen = false;
$('#headerExt').hide();
$('#header').click(function () {
if (!headerExtIsOpen) {
$('#headerExt').show();
headerExtIsOpen = true;
} else {
$('#headerExt').hide();
headerExtIsOpen = false;
}
});
}
There is no need to remember the state, just use toggle()
$(function () {
setMenu();
});
function setMenu()
{
$('#headerExt').hide();
$('#header').on("click", function (e) {
e.preventDefault();
$('#headerExt').toggle();
});
}
You said you want to toggle other things.
Best thing would be to toggle a class to change the color
$('#header').on("click", function (e) {
e.preventDefault();
$(this).toggleClass("open");
$('#headerExt').toggle();
});
another way is to check the state
$('#header').on("click", function (e) {
e.preventDefault();
var child = $('#headerExt').toggle();
var isOpen = child.is(":visibile");
$(this).css("background-color" : isOpen ? "red" : "blue" );
});
if the layout is something like
<div class="portlet">
<h2>Header</h2>
<div>
<p>Content</p>
</div>
</div>
You can have CSS like this
.portlet h2 { background-color: yellow; }
.portlet > div { display: none; }
.portlet.open h2 { background-color: green; }
.portlet.open > div { display: block; }
And the JavaScript
$(".portlet h2 a").on("click", function() {
$(this).closest(".portlet").toggleClass("open");
});
And there is layouts where it would be possible to have zero JavaScript involved.
Turns out I had some script hidden in my .js file that closes the menu again when the user clicks elsewhere, that I forgot about.
function resetMenu(e) {
var container = $('#headerExt');
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
$('#header').css("background-color", "inherit");
container.hide();
headerExtIsOpen = false;
}
}
I forgot to set the headerExtIsOpen back to false again after closing it in this function (code above shows the fix). Now it works fine :)
I am trying to make a select-unselect image by change border color on click by this code
var $box=null;
$('img')
.click(function() {
if ($box == null) {
$box = $(this);
$box.css("border","5px solid green");
} else {
$box.css("border","5px solid white");
$box = null;
}
}
);
The code is working fine except when I try to select-unselect and select same image. I want to select the other image by one click.
I tried to check if ($box == $(this)) but it does not work.
Use a class instead, and toggle the class when needed. This solution acts like a radio button (only one image with a border at a time), but allows you to deselect the active image as well:
http://jsfiddle.net/6cGVz/
$('img').click(function() {
var $this = $(this);
if ($this.hasClass('active')) {
$this.removeClass('active');
} else {
$('.active').removeClass('active');
$this.addClass('active');
}
});
Explanation
Check if $box is the clicked element or not. If it is, just hide its border if it has one. Otherwise, put the border on the clicked element!
Solution (Live Demo)
JavaScript/JQuery
var $box=null;
$('img')
.click(function() {
if ($box == null) {
$box = $(this);
$box.css("border","5px solid green");
} else {
$box.css("border","5px solid white");
if($box != $(this))
{
$box = $(this);
$box.css("border","5px solid green");
}
else
$box = null;
}
}
);
For the purposes of your question, I will put all of the images in a container:
<div id='setOfImages'>
<img ... >
<img ... >
<img ... >
<img ... >
</div>
Toggle a class.
$('#setOfImages > img').click(function() {
'use strict';
if($(this).hasClass('selected')) {
// Deselect currently selected image
$(this).removeClass('selected');
} else {
// Deselect others and select this one
$('#setOfImages > img').removeClass('selected');
$(this).addClass('selected');
}
});
And in your CSS:
#setOfImages > img {
border: 5px solid #fff;
}
#setOfImages > img.selected {
border: 5px solid green;
}
See jsFiddle demo.
Update - only one image can be selected
toggleClass of jQuery method make it so easy -
Using Js -
$('img').click(function() {
if ($(this).hasClass("selected")) {
$("img.selected").removeClass("selected");
} else {
$("img.selected").removeClass("selected");
$(this).addClass("selected");
}
});
with css -
.selected{
border:5px solid green;
}
Demo
You can add a data attribute to the image itself, instead of relying on something external.
$('img')
.click(function() {
var img = $(this);
if (! img.data('box')) {
img.css("border","5px solid green");
img.data('box', true);
} else {
img.css("border","5px solid white");
img.data('box', false);
}
}
);
A working example: http://codepen.io/paulroub/pen/qbztj