Why does replaceWith cancels calls to its variable? - javascript

I'm trying to clone dom elements and change their tags. But after I replace the main element I cannot change its children nor apply some click events.
I commented line after which it stops working.
Thanks for help!
http://codepen.io/sanns/pen/eJvzBN?editors=101
var selectDom = $('select');
selectDom.each(function() {
var clone = $(this).clone().insertAfter(this);
//take classes from clone
var classesStr = clone.attr('class');
clone = clone.replaceWith(function(index, oldHTML) {
return $('<div class="custom-select ' + classesStr + '">').html(oldHTML);
});
//why does not work?
clone.find('option').replaceWith(function(index, oldHTML) {
return $('<li>').html(oldHTML);
});
clone.wrapInner('<ul class="scrollbox"></ul>').prepend('<span class="shower"> Выберитеtttttttttteeeee тратататататат</span>');
//BEHAVIOR SELECT
clone.on('click', function() {
alert('asdf');
});
});

Actually .replaceWith() returns the original jQuery object, not the replacement with something.
You can find more details : http://api.jquery.com/replacewith/
Here is the small example of it:
$( "button" ).click(function() {
$( this ).replaceWith( "<div>" + $( this ).text() + "</div>" );
});
button {
display: block;
margin: 3px;
color: red;
width: 200px;
}
div {
color: red;
border: 2px solid blue;
width: 200px;
margin: 3px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>First</button>
<button>Second</button>
<button>Third</button>

Related

How to change content of div on hover using JQuery/Javascript

I'm trying to change the contents of a div when it's hovered over using JQuery. I've seen answers on stack overflow, but I can't seem to get it working.
I've tried
$( "imgDiv" ).mouseover(
function() {
$("tdiv").textContent = "hovering";
},
function() {
$("tdiv").textContent = 'title';
}
);
I've also replaced "mouseover" with "hover". I've used a variable and the actual div in place of "imgDiv".
This is what my code looks like:
imgDiv = document.getElementById('imgDiv');
tDiv = document.getElementById('titleDiv');
$( "imgDiv" ).mouseover(
function() {
$("tdiv").textContent = "hovering";
}, function() {
$("tdiv").textContent = 'title';
}
);
body {
background: white;
padding: 20px;
font-family: Helvetica;
}
#imgDiv {
width: 100px;
height: 100px;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv">
<div id=titleDiv>title</div>
</div>
You can use jQuery's .hover() function along with the .text() function to do what you want. Also, no need for document.getElementById:
$("#imgDiv").hover(
function() {
$("#titleDiv").text("hovering");
},
function() {
$("#titleDiv").text('title');
}
);
body {
background: white;
padding: 20px;
font-family: Helvetica;
}
#imgDiv {
width: 100px;
height: 100px;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv">
<div id="titleDiv">title</div>
</div>
You can target the div with jQuery, and store it's original value. On mouseout, you can restore it. Also using mouseenter reduces the number of times the logic processes as mouseover will fire for every mouse move over the element.
var $titleDiv = $('#titleDiv');
$("#imgDiv")
.on('mouseenter', function() {
$titleDiv.data('originalText', $titleDiv.text());
$titleDiv.text('hovering');
})
.on('mouseout', function() {
$titleDiv.text($titleDiv.data('originalText'));
});
body {
background: white;
padding: 20px;
font-family: Helvetica;
}
#imgDiv {
width: 100px;
height: 100px;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv">
<div id="titleDiv">title</div>
</div>
First of all, replace $("imgDiv") with $("#imgDiv") to get the element with id (#) imgDiv.
Then $("tdiv") doesn't exist, you probably mean $("div") to select a <div>tag in your DOM.
And finally, $("tdiv").textContent doesn't exist. You can try $("div").html() or $("div").text() to get the <div> tag content
--
Quick reminder : jQuery documentation on selectors
$("div") will select the <div> tags
$(".element") will select tags with class="element"
$("#element") will select tags with id="element"
You need to try like this
$( "#imgDiv" ).mouseover(function() {
$("#titleDiv").text("hovering");
}).mouseleave( function() {
$("#titleDiv").text('title');
});
body {
background: white;
padding: 20px;
font-family: Helvetica;
}
#imgDiv {
width: 100px;
height: 100px;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv">
<div id=titleDiv>title</div>
</div>
Easy solution,
var s = document.getElementsByTagName('div');
function out() {
s[0].innerHTML = 'hello';
}
function ibn() {
s[0].innerHTML = 'Myname';
}
<div onmouseout = 'out()' onmouseenter = 'ibn()'> Myname </div>
You cannot call reference a dom with pure Javascript and them manipulate it with jQuery - it will not work.
Try this:
$( "#imgDiv" ).mouseover(function() {
$("#titleDiv").text("hovering");
});
The titleDiv id has to be referenced in your code using "#", then the id name.
Also, use $("#name_of_id").text("your content") instead of .textContent()

Adding child to parent in Jquery using variables

I'm trying to dynamically creating a div inside a div using Jquery. When I dump the child nodes for div1, it shows only text and strong. I was expecting 'div1' to have main_div_elem child and main_div_elem to have col_md_8_elem child.
Can someone help me to add col_md_8_elem to be child of main_div_elem and main_div_elem as child of 'div1'?
Output of console log from my JS function.
NodeList [ #text "Here", ]
Code:
var id = 1;
function tryThis() {
$( "#div1" ).append( "<strong>Hello</strong>" );
var main_div_elem = $('<div /', {id : 'main_div_elem'.concat(id), "class" : "row"});
var col_md_8_elem = $('<div /', {id : 'col_md_8_elem'.concat(id), "class" : "col-md-8"});
main_div_elem.append(col_md_8_elem);
$('#div'.concat(id)).append(main_div_elem);
var children = document.getElementById("div1").childNodes;
console.log(children);
}
Trying to achieve following HTM code using jquery.
<div class="row">
<div class="col-md-8">
</div>
</div>
Thanks,
Deepak
Hello You can try the below code .I write it differently but hope it will help you
$(document).ready(function() {
var id = 1;
var main_div_elem = "<div id=main_div_elem class='row'></div>"
var main_div_elem8 = "<div id='col_md_8_elem' class='col-md-8'></div>"
$("#div1").append(main_div_elem);
$("#main_div_elem").append(main_div_elem8);
var children = $("#div1").html();
console.log(children);
});
#div1 {
height: 100px;
width: 100px;
position: absolute;
padding: 10px;
background-color: red;
}
#main_div_elem {
height: 50px;
width: 50px;
position: absolute;
padding: 10px;
background-color: green;
}
#col_md_8_elem {
height: 20px;
width: 20px;
position: absolute;
padding: 10px;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="div1"></div>
Your main_div_elem and col_md_8_elem are not created correctly. The first parameters to the $(..) call are invalid HTML. You need to add a closing angle bracket (>) like this:
var id = 1;
function tryThis() {
$("#div1").append("<strong>Hello</strong>");
var main_div_elem = $('<div />', {
id: 'main_div_elem'.concat(id),
"class": "row"
});
var col_md_8_elem = $('<div />', {
id: 'col_md_8_elem'.concat(id),
"class": "col-md-8"
});
main_div_elem.append(col_md_8_elem);
$('#div'.concat(id)).append(main_div_elem);
var children = $("#div1").html();
console.log(children);
}
$(function() {
tryThis();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1"></div>

Jquery Drag to Delete

I am currently playing with some jquery and as i tried to create a simple todo-list I came across a problem.
So far the goal is to be able to add paragraphs by clicking the green square and remove them by clicking it once and then dragging it to the red square.
Everything works out fine except the deleting of the dragged paragraph.
Right now it only works by removing the whole class but I want to only delete the dragged one.
Here the code: https://codepen.io/anon/pen/OXXXpY
jQuery:
$(document).ready(function() {
var send = $("#send");
var dlt = $("#delete");
send.click(function() {
var input = $("input").val();
$("#container").prepend("<p class='entry'>" + input + "</p>");
});
$(document).on("click", ".entry", function() {
$(this).draggable();
$("#delete").droppable({
drop: function() {$(".entry").remove();}
});
});
});
Please don't mind my English and the real use of this project. This is just an jQuery experiment.
Use $(this) to target the dragged element
$(document).on("click", ".entry", function() {
var $this = $(this);
$(this).draggable();
$("#delete").droppable({
drop: function() {
$($this).remove();
}
});
});
$(document).ready(function() {
var send = $("#send");
var dlt = $("#delete");
send.click(function() {
var input = $("input").val();
$("#container").prepend("<p class='entry'>" + input + "</p>");
});
$(document).on("click", ".entry", function() {
var $this = $(this);
$(this).draggable();
$("#delete").droppable({
drop: function() { $($this).remove(); }
});
});
});
body {
text-align: center;
}
h1 {
font-family: Helvetica;
}
form input {
width: 500px;
font-size: 30px;
}
form input:focus {
outline: none;
}
.inline {
display: inline-block;
}
#send {
width: 40px;
height: 40px;
background-color: green;
}
#delete {
width: 40px;
height: 40px;
background-color: red;
}
.entry {
font-family: helvetica;
border: solid 1px grey;
-webkit-user-select: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<h1>ToDo</h1>
<form class="">
<div class="inline" id="delete"></div>
<input type="text" name="input" value="">
<div class="inline" id="send"></div>
</form>
<div id="container"></div>

Getting CSS Properties and writing to the page live with jQuery

I am trying to get the names and values of CSS properties and write them to the page. The problem is the values don't change live i.e., e.g. the opacity should show a decreasing value from 1 to 0 live. Also the padding, border and margin values are not shown. This can be seen by opening up the page in firefox and using firebug to inspect it.
The Markup
<div id="container">
<div id="box">click to hide me</div>
<p id="result"> </p>
</div>
The Styles
#container {
overflow: auto;
}
#box {
width: 400px;
height: 400px;
padding: 10px;
border: 5px solid black;
margin: 15px;
background-color: red;
text-align: center;
float: left;
}
#result {
width: 400px;
height: 200px;
border: 1px solid #CCCCCC;
background-color: #EEE;
float: right;
margin-right: 20px;
}
The Script
$(document).ready(function() {
$( "#box" ).click(function() {
var html = [ "The clicked div has the following styles:" ];
var styleProps = $( this ).css(["width", "height", "padding", "border", "margin", "opacity", "display"]);
$.each( styleProps, function( prop, value ) {
html.push( prop + ": " + value );
});
$( "#result" ).html( html.join( "<br>" ) );
});
$("#box").click(function() {
$("#box").hide(5000);
});
});
Just to be clear I am noob with jQuery/javascript and I am trying to find out which and what values the jQuery hide() method changes. Using firebug in firefox I see that the the height, width, border, padding, margin, opacity and display are nulled. I am trying to show that in the page itself in the result div.
fiddle
You have several issues here.
You cannot get margin, padding, and border css properties in one go. You need to get something like marginTop, paddingBottom, borderWidth and so on.
You need to get status update to separate function, an then call it on progress of your hide.
$.fn.update = function(element) {
var html = [ "The clicked div has the following styles:" ];
var styleProps = $( this ).css(["width", "height", "opacity", "display"]);
$.each( styleProps, function( prop, value ) {
html.push( prop + ": " + value );
});
element.html(html.join("<br>"));
}
var box = $("#box");
box.click(function() {
box.hide({
duration: 5000,
progress: function() {
box.update($("#result"));
}
});
});
Fiddle for ya

Get links to stay active

I have 4 options that, when clicked, the clicked option becomes focused and its background-color/text color change, while all the other revert to the normal states. I have some code where I can change font color, but I can't figure out how to change the div color. I'm also trying to figure out in CSS and with this code how to have one of the options be by default highlighted when the page loads.
Jquery- the last line "($("a")" is the line of code that changes font color; the code above it has to do with a filtering system I have on the page.
$(function () {
var $panels = $( '#image-wrapper .panel' );
$( '#category > div > a' ).on( 'click', function (event) {
event.preventDefault();
var categoryToShow = $( this ).data( 'filter' );
$panels.addClass( 'active' ).filter( '.' + categoryToShow ).removeClass( 'active' );
$("a").addClass("active-color").not(this).removeClass("active-color");
/*$("#category .current-div").addClass("active-bg").not(this).removeClass("active-bg");*/
} );
});
HTML
<div id="category">
<div class="all-div current-div">
<h2>ALL</h2>
</div>
<div class="ed-div current-div">
<h2>EDITORIAL</h2>
</div>
<div class="pr-div current-div">
<h2>PR</h2>
</div>
<div class="cr-div current-div">
<h2>CREATIVE</h2>
</div>
</div>
CSS
#content,
#category {
overflow: hidden;
}
#category div {
float: left;
margin: 40px 0 0 0;
height: 100px;
width: 240px;
background-color: #F5F5F5;
}
#category .all-div {
background-color: #000000;
}
#category .all-div a {
color: #ffffff;
}
.active-color {
color: #000000;
background-color: green;
}
.active-bg {
background-color: green;
}
Well, .on was not working on your selector so i changed it to .live and changed your selector for the backgrounds to .current-div because your a tags need display: block to have a visible background.
check this:
http://jsfiddle.net/A3n7S/15/
$(function () {
var $panels = $( '#image-wrapper .panel' );
$(".current-div").not('.all-div').first().addClass("active-color")
$( '#category > div > a' ).live( 'click', function (event) {
event.preventDefault();
var categoryToShow = $( this ).data( 'filter' );
$panels.addClass( 'active' ).filter( '.' + categoryToShow ).removeClass( 'active' );
$(".current-div").not('.all-div').removeClass("active-color");
$(this).parent().addClass("active-color");
/*$("#category .current-div").addClass("active-bg").not(this).removeClass("active-bg");*/
} );
});
Replace that:
.active-color {
color: #000000;
background-color: green;
}
with:
#category .active-color {
color: #000000;
background-color: green;
}

Categories