Using js onclick on one button to inject link into another - javascript

I have two buttons, both without links, and want to add a link to one when the other is clicked. How can I make one button with an onclick give a link attribute to something else on the page? If not a button, maybe a div?
The following is my current code:
<div class="container">
<div class="jumbotron" style="background-color:#000000 !important;">
<img id="myImage" src="images/closed.png" style="width:100%">
<p id="texthere"></p>
<div class="container">
<div class="row">
<div class="col">
<button onclick="document.getElementById('myImage').src='images/open.png'" class="btn btn-primary active btn-block">Open Eyes</button>
</div>
<div class="col">
<button onclick="document.getElementById('myImage').src='images/closed.png'"class="btn btn-primary active btn-block">Close eyes</button>
</div>
</div>
</div>
Thank you in advance for your help.
*Edited to clarify and pose as a question.

I think you may be confused about how HTML links work. HTML has the a tag for elements that a user can click to go to a different URL. The (worse) alternative is to use an onclick handler to redirect the user by setting the value of window.location.
To make a button that creates a link on the page, put a script tag at the bottom of the body that attaches a listener to a button that, when called, places a link on the page.
<script type="text/javascript">
var button = document.getElementById('my-button'); // This button has to exist.
button.addEventListener('click', function() {
var link = document.createElement('a');
link.href = 'google.com'; // Or wherever you want the link to point.
document.body.appendChild(link);
});
</script>

While there are many ways to do what you want, without knowing what programming skills you have and what you want to see on the screen, perhaps this sort of structure would help you. Replace your current onclick handlers on the BUTTONs:
<button id="open" class="btn btn-primary active btn-block">Open Eyes</button>
<button id="close" class="btn btn-primary active btn-block">Close eyes</button>
<script>
document.getElementById("open").addEventListener("click", function() {
changeState('open');
});
document.getElementById("close").addEventListener("click", function() {
changeState('closed')
});
function changeState(state) {
document.getElementById("myImage").src = 'images/' + state + '.png';
var new_para = document.createElement("p");
var new_link = document.createElement("a");
new_link.setAttribute("href", "https://www.google.com/search?" + state);
var new_link_text = document.createTextNode("Search for '" + state + "'");
new_link.appendChild(new_link_text);
new_para.appendChild(new_link);
document.body.appendChild(new_para);
}
</script>

Related

How to add active element id to url

I was trying to add the id value of active element into a url. Then using a button to redirect to the url.
HTML
<div class="icon" tabindex="0" id="company">
<img src="company.png">
</div>
<button type="submit" onclick="myFunction()">jump</button>
Javascript
function myFunction(){
var x = document.activeElement.id;
location.href = "apps-online.html?page=" + x;
}
My expectations was: when I click the button, it will redirect to page
"apps-online.html?page=company"
However, the url of the new page is
"apps-online.html?page="
I was wondering why the value of x hasn't been added to the url.
Hi, everyone. For now I have understood why this problem happened. Because every time when I click the button, the button became the last active element.
So is there any way to achieve my goal?
Do check the value of x whether it is empty or not if it is empty the value of x will be passed as empty so there is no value in the url .try debugging the code or use console.log
function myFunction(){
var x = document.activeElement.id;
console.log(x);
location.href = "apps-online.html?page=" + x;
}
this gives the value of x in the console check this.
Your button does not have an id.
Give id="company" to button element.
<div class="icon" tabindex="0">
<img src="company.png">
</div>
<button id="company" type="submit" onclick="myFunction()">jump</button>
When you click on the button, the active element is button itself. I am assuming you have several divs and you need to pass the id of the highlighted element. You need to send the id to the function in some way.
Take a look below. This can be one of the many possible solutions.
HTML
<div class="icon" tabindex="0" id="company">
<img src="company.png">
</div>
<div class="icon" tabindex="1" id="something">
<img src="something.png">
</div>
<button type="submit" onclick="myFunction()">jump</button>
JS
let tabID = null;
let icons = document.getElementsByClassName('icon');
for (icon of icons)
{
icon.onclick = function()
{
tabID = document.activeElement.id;
}
}
function myFunction()
{
window.open("apps-online.html?page=" + tabID);
}

Change href to anchor on same page

This is probably an easy question but I couldn't figure it out: I am trying to change a href to a variable using JavaScript/jQuery. I am using the Bootstrap Collapse Plugin. My code looks basically like this:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<h2>Collapsible Panel</h2>
<p>Click on the collapsible panel to open and close it.</p>
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#collapse1">Collapsible panel</a>
</h4>
</div>
<div id="collapse1" class="panel-collapse collapse">
<div class="panel-body">Panel Body</div>
<div class="panel-footer">Panel Footer</div>
</div>
</div>
</div>
</div>
however panels are created dynamically and at some point, I have to change the ids and hrefs. E.g.:
...
to
...
If I use Javascript
var link = newId();
//newId is part of the plugin, but is based on the previous href
element.href = "#" + link;
the html changes into
...
(which is the full address of the page, with the anchor)
and it does not work anymore. However hardcoding it like this would work:
element.href = "#361cd655-ad54-4cd5-aeb7-a3da9553c1e9";
I've tried quite a few things but I always get similar results.
I can figure out that newId() most likely involves the previous href attribute because if you were to have an anchor element:
<a href='page'></a>
Even though it is a relative URL, the code
document.getElementsByTagName("a")[0].href
would return the full URL (eg. https://serveradmin.xyz/page)
A possible solution is instead of getting the current href, when changing it, also have a variable set to the new value. For example:
var linkHref = 1;
document.getElementsByTagName("a")[0].href = linkHref;
//when you next want to change it, don't get the current href, instead, use the link variable
linkHref++;
document.getElementsByTagName("a")[0].href = linkHref;
Alternatively, you could do this:
function getRelativeHref(href) {
return href.replace(window.location.href + "#", "");
}
If the href parameter was https://stackoverflow.com/posts/51951100/edit#test then it would return #test.
I think you have some problems in your newId function. You need something like that:
btn.addEventListener("click", () =>
Array.from(
document.querySelectorAll('a'),
a => a.href = "#" + newId())
)
function newId () {
return Math.random().toString(36); // simple random string.
};
...
<button id="btn">Change!</button>

Swap div and contents on click

Been trying to swap 2 divs. When the button is clicked #profeditclick1, #profswitch1 should swap with #hideedit1. At the moment when the button is clicked all the divs just disappear. Thank for your help or guidance.
HTML:
<div class="cart_verwrap" >
<div class="cart_verbill" *id="profswitch1">
<div class="btn blue cartprof-btn l-btn txt_fff s16" id="profeditclick1">Edit</div>
</div>
<!-- hidden edit profile in css it set to display:none-->
<div class="cart_verbill" id="hideedit1">
</div>
jQuery:
$("#profeditclick1").click(function(e) {
e.preventDefault();
var content = $(this).html();
$('#profswitch1').replaceWith('<div id="hideedit1">' + content + '</div>');
});
UPDATE
Next attempt although doesnt seem to work. i have taken of the display:none and tried to hide it:
$("#hideedit1").hide();
$("#profeditclick1").click(function(e) {
e.preventDefault();
var content = $(this).html();
$('#profswitch1').replaceWith('<div id="hideedit1">' + content + '</div>');
$("#hideedit1").show();
});
I think this may help you. I have added some modification in your HTML.
Please check it and change it as you need.
jQuery('#hideedit1').hide();
jQuery('#profeditclick1').click(function(){
jQuery(this).hide();
jQuery('#hideedit1').show();
});
jQuery('#hideedit1 #save_edit').click(function(){
jQuery('#hideedit1').hide();
jQuery('#profeditclick1').show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="cart_verwrap" >
<div class="cart_verbill">
<div class="btn blue cartprof-btn l-btn txt_fff s16" id="profeditclick1">Edit</div>
</div>
<!-- hidden edit profile in css it set to display:none-->
<div class="cart_verbill" id="hideedit1"> EDIT PROFILE CONTENT <button id="save_edit">Save</button> </div>
</div>

Modal not visible in Twitter boootstrap

I am trying to display a modal on image click with the image which is clicked, but its not working.
fiddle
I am inserting the content of modal after the user clicks the image using
$("#imageModal").html(modalHtml);
$('#imageModal').modal('show');
This code might now work as I am getting the error: showModal is not defined but the same code is working on my website.
Please help find the issue.
First at the very top of your html body....directly after the <body> tag, and before any content.
Put your modal...without any img, just an empty body...
<div id="imageModal" class="modal hide fade in">
<div class="modal-header"><a class="close" data-dismiss="modal">x</a>
<h3>Select the area</h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
Men Topwear
Men Bottowear
Women Topwear
Women Bottomwear<br>
Close
</div>
Then later in your document, wherever you want the images...just wrap them in a <a> tags, and apply the name of the modal box to the href, and apply the data-toggle attribute... data-toggle="modal"
<a class='galleryImg' href="#imageModal" data-toggle="modal">
<img src="http://media.santabanta.com/gallery/global%20celebrities(f)/shakira/shakira-28-m.jpg" />
</a>
<a class='galleryImg' href="#imageModal" data-toggle="modal">
<img src="http://media.santabanta.com/gal/event/ramaiya-vastavaiya-sp" />
</a>
Then in your Jquery...simply find all the links with the class .galleryImg, or however you want to identify them, and apply a click handler...that passes the image, to the modal.
$('a.galleryImg').click(function (e) {
e.preventDefault();
var img = $(this).html();
$('.modal-body').html(img);
});
Heres the JSFIDDLE DEMO
UPDATE
After looking at the code you pasted....you cant do it like that, as you are outputting two click handlers, on created items. You need to do it like this...
function testAPI(){
listOfPage = ["http://media.santabanta.com/gallery/global%20celebrities(f)/shakira/shakira-28-m.jpg", "http://media.santabanta.com/gal/event/ramaiya-vastavaiya-special-screening/ramaiya-vastavaiya-special-screening-32.jpg"]
for (var i=0;i<listOfPage.length;i++){
$("#imgbox").append('<a class="galleryImg" href="#imageModal" data-toggle="modal"><img src="'+listOfPage[i]+ '"></a>');
}
}
And then sepereately have this outside of the loop....
$('body').on('click', 'a.galleryImg', function (e) {
e.preventDefault();
var img = $(this).html();
$('.modal-body').html(img);
});
Because since you are appending the items, they are dynamically created so you need to use on instead of click
But you also need to wrap it all in a $(document).ready(function()...like so
$(document).ready(function(){
//Facebook login function run/loop
function testAPI(){
listOfPage = ["http://media.santabanta.com/gallery/global%20celebrities(f)/shakira/shakira-28-m.jpg", "http://media.santabanta.com/gal/event/ramaiya-vastavaiya-special-screening/ramaiya-vastavaiya-special-screening-32.jpg"]
for (var i=0;i<listOfPage.length;i++){
$("#imgbox").append('<a class="galleryImg" href="#imageModal" data-toggle="modal"><img src="'+listOfPage[i]+ '"></a>');
}
}
//Apply click handler to dynamic links...
$('body').on('click', 'a.galleryImg', function (e) {
e.preventDefault();
var img = $(this).html();
$('.modal-body').html(img);
});
});

Want to make inactive hyperlink

I have problem in hide and show the div element.
In this scenario when user click on the year the respect content is shown.
Problem I want to inactive hyperlinking on respective year when it is opened.
The script and html is below;
for this I have tried .preventDefault(). but not got any success:
<script type="text/javascript" >
$(document).ready(function() {
$("div.new:gt(0)").hide();// to hide all div except for the first one
$("div[name=arrow]:eq(0)").hide();
// $("div.nhide:gt(0)").hide();
// $("a[name=new]").hide();
$("a[name=new]").hide();
$('#content a').click(function(selected) {
var getID = $(this).attr("id");
var value= $(this).html();
if( value == '<< Hide')
{
// $("#" + getID + "arrow").hide();
$("a[name=new]").hide();
$("#" + getID + "_info" ).slideUp('slow');
$("div[name=arrow]").show();
$("div.new").hide();
$(this).hide();
// var getOldId=getID;
// $("#" + getID ).html('<< Hide').hide();
}
if($("a[name=show]"))
{
// $("div.new:eq(0)").slideUp()
$("div.new").hide();
$("div[name=arrow]").show();
$("a[name=new]").hide();
$("#news" + getID + "arrow").hide();
$("#news" + getID + "_info" ).slideDown();
$("#news" + getID ).html('<< Hide').slideDown();
}
});
});
</script>
The html code is below:
<div id="content">
<div class="news_year">
<a href="#" name="show" id="2012">
<div style="float:left;" name="year" id="news2012year">**2012** </div>
<div style="float:left;" name="arrow" id="news2012arrow">>></div>
</a>
</div>
<div class="new" id="news2012_info">
<div class="news">
<div class="news_left">News for 2012</div>
</div>
<div class="nhide" ><< Hide </div>
</div>
<div id="content">
<div class="news_year">
<a href="#" name="show" id="2011">
<div style="float:left;" name="year" id="news2012year">2012 </div>
<div style="float:left;" name="arrow" id="news2012arrow">>></div>
</a>
</div>
<div class="new" id="news2011_info">
<div class="news">
<div class="news_left">News for 2011</div>
</div>
<div class="nhide" ><< Hide </div>
</div>
Fiddle
if i am understanding your problem,
event.preventDefault(); not works with all browser so if you are using other browser like IE
then use event.returnValue = false; instead of that.so you can detect your browser using javascript as
var appname = window.navigator.appName;
This is what I'm currently using in my projects to "disable" an anchor tag
Disabling the anchor:
Remove href attribute
Change the opacity for added effect
<script>
$(document).ready(function(){
$("a").click(function () {
$(this).fadeTo("fast", .5).removeAttr("href");
});
});
</script>
Enabling the anchor:
$(document).ready(function(){
$("a").click(function () {
$(this).fadeIn("fast").attr("href", "http://whatever.com/wherever.html");
});
});
Original code can be found here
Add a class called 'shown' to your wrapper element when expanding your element and remove it when hiding it. Use .hasClass('shown') to ensure the inappropriate conditional is never executed.
Surround the code inside of the click function with an if statement checking to see if a variable is true or false. If it is false, it won't run the code, meaning the link is effectively inactive. Try this..
var isActive = true;
if (isActive) {
// Your code here
}
// The place where you want to de-activate the link
isActive = false;
You could also consider changing the link colour to a grey to signify that it is inactive.
Edit
Just realised that you want to have multiple links being disabled.. the code above will disable all of them. Try the code below (put the if around the code in the click function)
if(!$(this).hasClass("disabled")) {
// Your code here
}
// The place where you want to de-activate the link
$("#linkid").addClass("disabled");
// To re-enable a link
$("#linkid").removeClass("disabled");
// You can even toggle the link from disabled and non-disabled!
$("#linkid").toggleClass("disabled");
Then in your CSS you could have a declaration like this:
.disabled:link {
color:#999;
}

Categories