dynamically create element using jquery - javascript

I am trying to create element using jquery. When i click on a link, i want to create an element "p", give it some text, and then put it in one of my divs. Also, i want to check which link is clicked on, so i can put the created "p" in the right div. Any solutions on where i am doing it wrong?
Javascript/Jquery
$(document).ready(function () {
function createElement() {
var a = $("#menu").find('a').each(function(){
if(a == "l1"){
var text = $(document.createElement('p');
$('p').text("Hej");
$("#contentl1").append("text");
}
});
}
$("#menu").find('a').each(function () {
$(this).click(function () {
createElement();
});
});
createElement();
});
HTML
<html>
<head>
<title>Inl1-1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="style-1.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="Uppg1.js"></script>
</head>
<body>
<ul class="meny" id="menu">
<li>Utvärdering/Feedback</li>
<li>Kontakt</li>
<li>Öppettider</li>
<li>Om Asperöd</li>
</ul>
<div id="contentl1">
</div>
<div id="contentl2">
</div>
<div id="contentl3">
</div>
<div id="contentl4">
</div>
</body>
</html>

Here is the best way to add new <p> element with text "Hej" to #contentl1 using jQuery:
$("<p />", { text: "Hej" }).appendTo("#contentl1");

function createElement() {
var a = $("#menu").find('a').each(function(){
if(a == "l1"){
var p = $("<p>");
p.text("Hej");
$("#contentl1").append(p);
}
});
}

For a start the click function can be done like this instead of having to use .find():
$('#menu a').click(function() { }
The .each() loop can be done like:
$('#menu a').each(function () {
var aId = $(this).attr('id');
var contentId = content + aId;
$(contentId).append('<p>Hej</p>');
})

I know it doesn't realate to answering your question but it is hard to leave this as a comment:
var a = $("#menu").find('a').each(function(){ <-- this "a" will only be created after the each completes
if(a == "l1"){ <-- this "a" that you are verifying is a global variable
var text = $(document.createElement('p');
$('p').text("Hej");
$("#contentl1").append("text");
}
});
You can try this to solve your issue:
function createElement() {
if($(this).attr("id") == "l1"){
$("#contentl1").append('<p>hej</p>');
}
}
$("#menu a").each(function () {
$(this).click(function () {
createElement.apply(this);
});
});

Something like this fiddle?
$('#menu').on('click', 'a', function(e) {
e.preventDefault();
$('<p>').text($(this).text()).appendTo('#content'+this.id);
});

try this script, it'll do place the text in correct div.
$(document).ready(function () {
$("#menu").find('a').each(function () {
$(this).on('click',function () {
$("#content"+$(this).attr("id")).append("<p>link "+$(this).attr("id")+" is clicked</p>");
});
});
});

I personally like to use classic JS DOM for tasks so this is how you can first create the DOM object using JQuery. The DOM object returned is the outer element of HTML (p tag) but the inner HTML can be as complex as you want.
var elP = $("<p>Hej</p>")[0]
// Do some other DOM manipulations of p
// eg: elP.someCustomTag='foobar'
$("#content1").append(elP)

Related

addEventListener() with "click" can't run but no error show up to shuffle text with Chaffle.js

I'm having trouble with Chaffle.js library
I tried with jQuery and pure Javascript to add 1 more event is click to shuffle text when I click on a button with id="test" but they can't work and I don't see any errors show up in F12.
I hope you guys can help me.
Here is my code on Plunker
http://plnkr.co/edit/Yc8OrVW6QgVt0V6t
<html>
<head>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chaffle#2.1.0/src/chaffle.min.js"></script>
</head>
<body>
<button id="test">Shuffle</button>
<h1 class="shuffle">This created for shuffle effect but it isn't work</h1>
<h3 data-chaffle="en">About Me</h3>
<script>
var elements = document.querySelectorAll("[data-chaffle]");
Array.prototype.forEach.call(elements, function (el) {
var chaffle = new Chaffle(el);
el.addEventListener("mouseover", function () {
chaffle.init();
});
});
document.querySelectorAll("#test").addEventListener("click", function () {
var elm = document.querySelectorAll(".shuffle");
Array.prototype.forEach.call(elm, function (el) {
el.dataset.chaffle ='en';
var chaffle = new Chaffle(el);
el.addEventListener("click", function () {
chaffle.init();
});
});
});
</script>
</body>
</html>
Thank you!!
there is maybe a bug in chaffle.js line 54
if (dataLang.length !== 0) data.lang = dataLang
its not check dataLang for null, so it required to adddata-chaffle attribute to the element
var elm = document.querySelectorAll(".shuffle");
Array.prototype.forEach.call(elm, function (el) {
el.dataset.chaffle ='en'; // <== append this

How can I re-attach element with jQuery? [duplicate]

This question already has answers here:
Re-attaching jQuery detach();
(8 answers)
Closed 6 years ago.
Hey guys I am trying to re-attach an element when it has been detached from the DOM however I can't seem to find an easy solution to this.
$(document).on('click', '#emailEnquiryPreferred', function () {
$('.form-group-timepicker').fadeOut(300, function(){ $(this).detach(); });
});
As you can see with the following code I am detaching it however with another click event I would like to reattach it to the same position, how can this be done?
Thanks
Keep it as variable before attaching it:
var $detachedElement;
$(document).on('click', '#emailEnquiryPreferred', function () {
$('.form-group-timepicker').fadeOut(300, function(){
$detachedElement = $(this);
$(this).detach();
});
});
Now when you need to re-attach it simple use $detachedElement variable ...
Here is a full sample:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
var $detachedElement;
$(document).ready(function() {
$('#id2').on('click', function() {
$('#div').append($detachedElement);
})
$("p#id1").click(function() {
$detachedElement = $(this).detach();
});
});
</script>
</head>
<body>
<div id="div" style="border: red solid 1px">
<p id="id1">Detach Me!</p>
</div>
<p id="id2">Re-attach it!</p>
</body>
</html>
You can store detached element:
var p = $(this).detach();
You need to store this element somewhere (for example in some object):
var detachedObj = null;
$(document).on('click', '#emailEnquiryPreferred', function () {
$('.form-group-timepicker').fadeOut(300, function(){
if(detachedObj == null)
detachedObj = $(this).detach();
else
{
$(this).attach(detachedObj);
detachedObj = null;
}
});
});
You can see similar example in jQuery API Documentation for .detach() (read example part): jQuery .detach()

How to remove tooltip generated by hover in jquery

I have used hover to display tooltip on hover. However the text keeps getting appended because the function I have written on mouseout is not working.
Below is my code:
var $j = jQuery.noConflict();
$j("#choice30QID404").hover(
function () {
// $j(this).append($("<span> HOVERING!!!!! </span>"));
$j(this).append("<span>HOVERING!!!!!</span>");
});
$j("#choice30QID404").click(function() {
$j(this).mouseout();
});
You can achieve this simply using title attribute. Unless and until you don't want to customize. I am writing without noConflict()
$('#choice30QID404').mouseover(function() {
$(this).attr('title','You are Hovering');
})
$('#choice30QID404').mouseout(function() {
$(this).removeAttr('title');
})
This will help you.
Do you want something like this.
Try this
Script
var $j = jQuery.noConflict();
$j("#choice30QID404").hover(
function () {
// $j(this).append($("<span> HOVERING!!!!! </span>"));
$j(this).append("<span class='span1'>HOVERING!!!!!</span>");
});
$j("#choice30QID404").mouseout(function() {
$j(this).find('.span1').remove();
});
HTML
<div id="choice30QID404">
Hover on this
</div>
Working Demo
Try This -->
You can append a on mouse hover and on mouseout remove that
var $j = jQuery.noConflict();
$j("#choice30QID404").hover(
function() {
// $j(this).append($("<span class='prepended'> HOVERING!!!!! </span>"));
$j(this).append("<span class='hovering'>HOVERING!!!!!</span>");
});
$j("#choice30QID404").mouseout(function() {
// $j(this).mouseout();
$j(".hovering").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:void(0)" id="choice30QID404">Hello<a>
You have appended DOM children to your element with the id of choice30QID404. You can then remove it on a .mouseout() event (reference).
JQuery helps with .children().remove().
var $j = jQuery.noConflict();
var $choice = $j("#choice30QID404");
$choice.hover(function () {
$j(this).append("<span>HOVERING!!!!!</span>");
});
$choice.click(function() {
$j(this).mouseout();
});
$choice.mouseout(function() {
$j(this).children().remove();
});
I hope this helps,
Rhys

change the background of an id that is clicked

When one of the element(id) of a form is clicked, i would like to listen to that event, and change the background of that element.
$(document).ready(function(){
$('form').on('click', function(e){
var x = e.target.id;
$(x).css('background-color',color);
return false;
});
}
<form>
<div id="a">Item1</div>
<div id="b">Item2</div>
<div id="c">Item3</div>
</form>
Your code will end up looking for tag names because the selector is
$("b")
If you want to do it the way you have it, you would need to add the missing #.
$("#" + x).css('background-color',color);
But there is no need to look up the element when you already have a reference to is. Use event delegation and this
$('form').on('click', 'div', function(e){
$(this).css('background-color',color);
});
Why bother using e.target? Just update your code to use $(this):
$(function() {
$('form > div').on('click', function(e) {
e.preventDefault();
$(this).css('backgroundColor', color);
});
});
This will work out. Take care of your tags.
$(document).ready(function(){
$('form').on('click', function(e){
var x = e.target.id;
$("#"+x).css('background-color',"red");
return false;
});
});
The thing happening to you is that event.target.id returns a string representing the id of the element, not a selector. So where you use $(x).... you have to use $('#'+x), your actual code does not work because the selector for the background change is not looking for an element with the X value on the Id but for an element called like the value of X (eg. x="a", then it's looking for elements)
Here's my "lowly" try:
<!DOCTYPE html>
<html lang = 'es'>
<head>
<title> My Test </title>
</head>
<body>
<form>
<div id="a"> Item1 </div>
<div id="b"> Item2 </div>
<div id="c"> Item3 </div>
</form>
<script>
function addBackgroundColor(e){
var index = parseInt(Math.random() * 4); // the number of the multiplier has to be equal to the length of the array colorsList.
e.target.style.backgroundColor = colorsList[index];
}
var colorsList = ['blue','red','green','yellow','orange']; //add others colors here if you want.
var divsList = document.getElementsByTagName('div');
for (var i in divsList){
divsList[i].addEventListener('click', addBackgroundColor);
}
</script>
</body>
</html>
No need to go fancy. Just do
$(document).ready(function(){
$('form div').on('click', function(e){
$(this).css('background-color',color);
return false;
});
}

Binding One Click Event to three different links

I wrote a simple script similar to this example. The problem is the click event is only binding to the first #id in the conditional statement. My thought on why this is occurring is there is nothing in each statement to associate the ID with the class in the click function, but when I tried to add a var, the click did not fire at all. Please tell me where I have gone wrong.
Thanks
$(document).ready(function(){
$('.someclass').bind('click', function() {
if('#id1')
{
window.location = "someURL";
}
else if('#id2')
{
window.location = "someURL2";
}
else if('#id3')
{
window.location = "someURL3";
}
});
});
You can check their id's like this
$(document).ready(function () {
$('.someclass').bind('click', function () {
if(this.id === 'id1') {
window.location = "someURL";
} else if(this.id === 'id2') {
window.location = "someURL2";
} else if(this.id === 'id3') {
window.location = "someURL3";
}
});
});
Consider:
<span data-url="someURL">Link 1</span>
<span data-url="someURL2">Link 2</span>
And then:
$wrapper.on( 'click', 'span', function () {
window.location = $( this ).data( 'url' );
});
where $wrapper contains the DOM element which in turn contains all your "links".
The idea here is to separate the data from the JavaScript code (= the behavior). Your URL's should be in the DOM - you can use data-* attributes to store them (as I've shown above).
Since you already use ids for your elements you should use them seperately to bind the click functions. It's easier and it works :)
$(document).ready(function(){
$('#id1').click(function(){
window.location = "someURL";
});
$('#id2').click(function(){
window.location = "someURL2";
});
$('#id3').click(function(){
window.location = "someURL3";
});
});
If you like the original way better (you shouldn't ;-) ) then try this:
if( $(this).attr("id") == 'id1' )
{
window.location = "someURL";
}
I think you are over thinking things and also not knowing what is out there for you to use. I would leverage the data attribute on your links. I'm going to assume they are not your typical A tag with an HREF because you should not use JavaScript if so.
<div data-url="http://www.someurl1.com">...</div>
<div data-url="http://www.someurl2.com">...</div>
<div data-url="http://www.someurl3.com">...</div>
<script>
$('body').on('click','div[data-url]', function(ev) {
ev.preventDefault();
window.location = $(this).data('url');
}
</script>
If my understanding is correct for your requirement, you have a css class called "someclass" which has hyperlinks into it. You need to set the URL of those hyperlinks dynamically through jQuery, am I correct? If so, then you can try the following code:
<script type="text/javascript" src="../Scripts/jQuery/jquery-1.7.2.js"></script>
<script type="text/ecmascript">
$(document).ready(function () {
$(".someclass > a").live("click", function () {
var currentID = $(this).attr("id");
if (currentID == "id1") {
window.location = "http://google.com";
}
else if (currentID == "id2") {
window.location = "http://stackoverflow.com";
}
else if (currentID == "id3") {
window.location = "http://jquery.com";
}
});
});
</script>
<div>
<div class="someclass">
<a id="id1">id 1</a>
<a id="id2">id 2</a>
<a id="id3">id 3</a>
</div>
</div>

Categories

Resources